killuwa killuwa - 1 year ago 65
jQuery Question

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


<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>

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


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


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 Source

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.


$(document).on("click", "#addRoomInfo", function(){

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download