正则表达式 + 修改文本

regex + modify text

本文关键字:文本 修改 正则表达式      更新时间:2023-09-26
<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')));
});

例如,如果我单击一个,则链接是:

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

我该如何解决它?

这是工作示例 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));
    });
});

您使用的是$("a")而不是$(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));
    });
});

欢呼^^

原因是当您单击一个元素时,它会替换所有元素上的值。试试这个:

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