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
$('#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). 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
<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:
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.
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.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.