killuwa killuwa - 2 months ago 6
jQuery Question

why change the html element's id , the click bind with the old id also run

html代码:

<ul class="nav" id="side-menu">
<li><a href="#" id="add1">录入1</a></li>
<li><a href="#" id="add2">录入2</a></li>
<li><a href="#" id="add3">录入3</a></li>
</ul>

<button type="button" class="addinfobtn" id="addRoomInfo">addinfo1</button>


js代码:

$("#side-menu a").click(function(){
switch($(this).attr("id")){
case "add1":
$(".addinfobtn").text("addinfo1").attr("id", "addRoomInfo");
break;
case "add2":
$(".addinfobtn").text("addinfo2").attr("id", "addServiceInfo");
break;
case "add3":
$(".addinfobtn").text("addinfo3").attr("id", "addMenuInfo");
break;
}

$("#addRoomInfo").click(function(){
console.log($(this).attr("id"));
});


result: I change the .addinfobtn id ,but when I click the button, the click function run, and console the id that is already changed. why?

Answer

The selector is used for the registration of an event and is only used at the time the event is registered, not when the event is fired.

To avoid this problem use delegated event handlers, attached to a non-changing ancestor of the dynamic elements.

e.g.

$(document).on("click", "#addRoomInfo", function(){
  console.log($(this).attr("id"));
});

This evaluates the filter at click time, not when the event was registered, so is a useful technique for any dynamically changing selectors.

Document is the default if nothing is closer, or more convenient, but do not use body for delegated events as it has a bug to do with styling that means mouse events may not fire.

It seems a little unusual to change the text and ID of the elements. You might be better off authoring all the elements and just hide and show them as required. This simplifies maintenance.