我有这个代码:
$("#container").on("click","#button1",action1);
$("#container").on("click","#button2",action2);
function action1(){
// do something
// change button1 id to button2
$("#button1").prop("id","button2");
}
function action2(){
// do something
}
所以当我点击button1时,action1会将button1更改为button2。
但问题是更改id后,事件action2(只有在单击#button2时才必须执行)正在执行
最佳答案
But the problem is after changing the id, the event action2 (which only must be executed when clicking #button2) is being executed
原因是您没有将处理程序 Hook 到按钮元素,而是将其 Hook 到容器,然后告诉 jQuery 当事件发生时>,它应该检查事件在冒泡过程中是否经过与 #button1
选择器匹配的元素。当您将button1的id
更改为button2
时,它不再匹配 - 但它确实与other处理程序匹配,因此另一个处理程序被调用。调度的这种动态特性使得事件委托(delegate)如此有用。
您可以通过以下方式“修复”此问题
不更改
id
,这是一件不寻常的事情。直接 Hook 处理程序而不是使用事件委托(delegate)。当然,如果您有使用委派的理由,那么这不是一个好的选择。 :-)
使用其他内容(例如类)来标识委托(delegate)
on
调用中的按钮。
请注意,但是,id
值必须是唯一的。因此,如果您要更改 button1
的 id
,则无法将其更改为 button2
- 即 id
已被使用。在下面的示例中,我使用了 newbutton1
。
#2 示例(如果您并不真正需要委派):
$("#button1").on("click",action1);
$("#button2").on("click",action2);
function action1(){
// do something
alert("action1, the id of the button is: " + this.id);
// change button1 id to newbutton1
$("#button1").prop("id","newbutton1");
}
function action2(){
// do something
alert("action2, the id of the button is: " + this.id);
}
<div id="container">
<input type="button" id="button1" value="button1">
<input type="button" id="button2" value="button2">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
#3 的示例:
$("#container").on("click", ".first-button", action1);
$("#container").on("click", ".second-button", action2);
function action1(){
// do something
alert("action1, the id of the button is: " + this.id);
// change button1 id to newbutton1
$("#button1").prop("id","newbutton1");
}
function action2(){
// do something
alert("action2, the id of the button is: " + this.id);
}
<div id="container">
<input type="button" id="button1" class="first-button" value="button1">
<input type="button" id="button2" class="second-button" value="button2">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
关于javascript - 用Javascript绑定(bind)事件,改变元素的id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32026626/