jQuery: change a div's id twice not working
I've been trying to toggle a div's id when the user clicks on it. First click works, and it changes the divs id, but when pressing again it wont change the div's id again....
$("#hello").click(function(){
$(this).attr("id","bye").text("bye");
});
$("#bye").click(function(){
$(this).attr("id","hello").text("hello");
});
<div id="hello">hello</div>
Any ideas of how to ge开发者_运维技巧t this working?
The handler is assigned to the element when the document loads, so there's no handler assigned to bye
since there's no element.
You can use .live()
(note that .delegate()
is better if there's some ancestor it can be applied to.):
Example: http://jsfiddle.net/patrick_dw/Pwa5Q/2/
$("#hello").live('click',function(){
$(this).attr("id","bye").text("bye");
});
$("#bye").live('click',function(){
$(this).attr("id","hello").text("hello");
});
Or just assign the handler to the element with hello
, and use the same handler to toggle the ID.
Example: http://jsfiddle.net/patrick_dw/Pwa5Q/
$("#hello").click(function(){
var newID = this.id === 'hello' ? 'bye' : 'hello';
$(this).attr("id",newID).text(newID);
});
It does not work because click event handler for 'bye' is bound before div's id is set to 'bye' in DOM. You can use live()
to get around this:
$("#hello").live('click', function(){
$(this).attr("id","bye").text("bye");
});
$("#bye").live('click', function(){
$(this).attr("id","hello").text("hello");
});
精彩评论