jQuery:改变div的id两次不工作

Her*_*ntz 1 html jquery click

当用户点击它时,我一直试图切换div的id.首次点击有效,它会改变div的id,但再次按下时它不会再改变div的id ....

$("#hello").click(function(){
    $(this).attr("id","bye").text("bye");
});

$("#bye").click(function(){
    $(this).attr("id","hello").text("hello");
});

<div id="hello">hello</div>
Run Code Online (Sandbox Code Playgroud)

有关如何使其工作的任何想法?

use*_*716 7

当文档加载时,处理程序被分配给元素,因此没有分配处理程序,bye因为没有元素.

你可以使用.live()(注意.delegate()如果有一些祖先可以应用它会更好.):

示例: 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");
});
Run Code Online (Sandbox Code Playgroud)

或者只是将处理程序分配给元素hello,并使用相同的处理程序来切换ID.

示例: http ://jsfiddle.net/patrick_dw/Pwa5Q/

$("#hello").click(function(){
    var newID = this.id === 'hello' ? 'bye' : 'hello';
    $(this).attr("id",newID).text(newID);
});
Run Code Online (Sandbox Code Playgroud)