2011-09-07 43 views
1
<span id="one"><a id="google" href="google.com/">link1</a></span> <br /> 
<span id="two"><a id="yahoo" href="yahoo.com/">link2</a></span> 

<br /> 
<br /> 
<span class="click" id=1>click one</span> <br /> 
<span class="click" id=2>click two</span> <br /> 
<span class="click" id=3>click three</span> <br /> 

$(".click").live('click', function() {  
    $("a").attr('href', $("a").attr('href').replace(/\d*$/, $(this).attr('id'))); 
}); 

如果我點擊例如點擊一個然後鏈接:正則表達式+的jQuery - 修改文字

<span id="one"><a id="google" href="google.com/1">link1</a></span> <br /> 
<span id="two"><a id="yahoo" href="google.com/1">link2</a></span> 

代替:

<span id="one"><a id="google" href="google.com/1">link1</a></span> <br /> 
<span id="two"><a id="yahoo" href="yahoo.com/1">link2</a></span> 

活生生的例子:http://jsfiddle.net/wtAbp/14/

我該如何修復它?

回答

2

這裏正在樣品http://jsfiddle.net/wtAbp/18/

$(".click").live('click', function() { 
    var $id = $(this).attr('id'); 
    $("a").each(function() { 
     $(this).attr('href', $(this).attr('href').replace(/\d*$/, $id)); 
    }); 
}); 
1

您使用$("a")代替$(this)

​​
1
$(".click").live('click', function() { 
    var id = $(this).attr('id'); 
    $("a").each(function() { 
     $(this).attr('href', $(this).attr('href').replace(/\d*$/, id)); 
    }); 
}); 

歡呼^^

1

的原因是,當你點擊一個它替換所有元素上的值。試試這個:

<span id="one"><a id="google" href="google.com/">link1</a></span> <br /> 
<span id="two"><a id="yahoo" href="yahoo.com/">link2</a></span> 

<br /> 
<br /> 
<span class="click" id=1>click one</span> <br /> 
<span class="click" id=2>click two</span> <br /> 
<span class="click" id=3>click three</span> <br /> 

$(".click").live('click', function() {  
    var $this = $(this); 
    $.each("a", function(index, element) { 
       $(element).attr('href',   $(element).attr('href').replace(/\d*$/, $this.attr('id'))); 
    }); 

});