javascript - 用Javascript绑定(bind)事件,改变元素的id

标签 javascript jquery html

我有这个代码:

$("#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)如此有用。

您可以通过以下方式“修复”此问题

  1. 不更改 id,这是一件不寻常的事情。

  2. 直接 Hook 处理程序而不是使用事件委托(delegate)。当然,如果您有使用委派的理由,那么这不是一个好的选择。 :-)

  3. 使用其他内容(例如类)来标识委托(delegate) on 调用中的按钮。

请注意,但是,id必须是唯一的。因此,如果您要更改 button1id,则无法将其更改为 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/

相关文章:

javascript - THREE.JS Loader onProgress 仅在加载完成后触发一次

javascript - AngularJS:将 XML 字符串加载到 XML 文档

javascript - 如何定位下一个 <div> 元素?

jquery - 如何在 Twitter Bootstrap 中从一个选项卡链接到另一个选项卡?

javascript - 在通过 JavaScript 提交之前更改表单值

html - 页面底部的水平滚动导航栏

javascript - 遍历数组以尝试页面上的多个选项并返回到每次迭代的初始页面

php - Jquery 表中 undefined index /值

jQuery TimePicker - 使用 dd/mm/yyyy

javascript - 没有任何服务器脚本的简单 HTML POST,可以使用 JS 完成