开发者

regex + jquery - modify text

开发者 https://www.devze.com 2023-04-03 09:25 出处:网络
<span id=\"one\"><a id=\"google\" href=\"google.com/\">link1</a></span> <br />
<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')));
});

If I click for example click one 开发者_开发技巧then links are:

<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>

instead of:

<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>

LIVE EXAMPLE: http://jsfiddle.net/wtAbp/14/

How can I fix it?


Here is working sample 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));
    });
});


You're using $("a") instead of $(this)

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


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

Cheer ^^


The reason is that when you click one it replaces the values on all a elements. Try this:

<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')));
    });

});
0

精彩评论

暂无评论...
验证码 换一张
取 消