简体   繁体   English

jQuery / Javascript替换功能仅可使用一次

[英]jQuery / Javascript replace function only works once

I have a button as such 我有一个这样的按钮

<button id="toggle_photo">
<span id="photo_text">Hide Photos (1)</span>
<img class="icon" alt="Photos" src="/img/photos-16.png">
</button>

And jQuery / Javascript to change the text upon clicking 以及jQuery / Javascript,可在点击后更改文本

$('#toggle_photo').click(function(){
    var text = $('#photo_text').text();
    $('#photo_text').text(
      text.match(/Hide Photos/) ? text.replace("Hide", "Show") : text.replace("Show", "Hide"));
    $('.photo_frame').toggle('slow');
  });

This works the first time the button is clicked and the button text changed from Hide Photo (1) to Show Photo (1) . 第一次单击该按钮,按钮文本从“ Hide Photo (1)更改为“ Show Photo (1)时,此方法起作用。 Next, the button html is replaced with new text via an AJAX call, new contents are the same except perhaps for the count, so it might show this instead 接下来,通过AJAX调用将html按钮替换为新文本,除了计数之外,新内容是相同的,因此它可能会显示此内容

<button id="toggle_photo">
<span id="photo_text">Hide Photos (3)</span>
<img class="icon" alt="Photos" src="/img/photos-16.png">
</button>

However, this time the element didn't trigger a click event, why? 但是,这次元素没有触发点击事件,为什么?

You already gave the answer yourself: 您已经自己给出了答案:

Next, the button html is replaced with new text via an AJAX call... 接下来,通过AJAX调用将html按钮替换为新文本...

You are removing the current element and adding a new one. 您要删除当前元素并添加一个新元素。 The elements might be of the same type and have the same ID, but they are still different elements. 元素可能具有相同的类型并具有相同的ID,但是它们仍然是不同的元素。

You either have to bind the event handler again after you changed the HTML, or you use .live() [docs] or .delegate() [docs] to bind the event handler. 您可能需要在更改HTML之后再次绑定事件处理程序,或者使用.live() [docs].delegate() [docs]来绑定事件处理程序。

Edit: I'm actually not sure whether you replace the whole button or just its contents. 编辑:我实际上不确定是替换整个按钮还是仅替换其内容。 But I assume this is the problem. 但是我认为这是问题所在。 If this does not help, you have to be more specific and also post the function which replaces the HTML. 如果这样做没有帮助,则您必须更加具体,然后发布替换HTML的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM