【问题标题】:JQuery - Changing element id isn't working [duplicate]JQuery - 更改元素ID不起作用[重复]
【发布时间】:2017-12-23 09:38:26
【问题描述】:

我正在尝试通过动态更改按钮的 ID 来更改按钮的功能。

<srcipt>
$("#old-id").click(function func_P(){
  //Some code
  this.id = "new-id";
});
$("#new-id").click(function func_Q(){
  // some other code
});
$("#clear").click(function func_R(){
  $(".in").attr("id","new-id");
});
</script>

<body>
  <button id="old-id" class="in">Button A</button>
  <button id="clear">Clear</button>
</body>

但我面临的问题是,当我单击“按钮 A”时,id 会更改,但当我再次单击“按钮 A”时,func_P() 会再次执行,而我打算调用 func_Q。

【问题讨论】:

  • 当您使用.click() 时,它会将事件分配给当时存在的元素。如果之后更改ID,则绑定事件时它不存在。所以你必须使用事件委托。

标签: javascript jquery


【解决方案1】:

使用.on函数绑定(live)点击。

$("#old-id").on('click', function func_P(e) {
  //Some code
  if (this.id == "old-id") {
    this.id = "new-id";
    console.log('old id clicked');
    e.stopPropagation()
  }
});
$(document).on('click', "#new-id", function func_Q() {
  // some other code
  console.log('new id clicked');
});
$("#clear").on('click', function func_R() {
  $(".in").attr("id", "old-id");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="old-id" class="in">Button A</button>
<button id="clear">Clear</button>

如果你想清除id,你应该改变:

$(".in").attr("id","new-id");

收件人:

$(".in").attr("id", "old-id");

【讨论】:

  • 你有没有注意到第一次点击也会运行#new-id的代码?因为当事件冒泡时,ID 已经改变,所以委托测试成功。你需要event.stopPropagation() 来阻止它。
  • @Barmar Have you noticed that the first click also runs the code for #new-id? 其实不,这很普通,当你点击$("#old-id") 时,它会将id 更改为new-id,因此它会执行#new-id 的代码。如果 OP 想要运行一些其他代码然后更改 id 所以需要使用 .done 或 .then 或等等。如果我使用 event.stopPropagation() 它将停止工作。随意在我的 sn-p 上尝试一下。
  • 是的,那是因为旧的事件处理程序即使在 ID 更改后仍在运行,所以它仍然停止传播。要么更改旧的处理程序以使用事件委托,要么将if (this.id == "old-id") 放在更改 ID 并停止传播的代码周围。
  • @Barmar 嗯.. 你说得对,那好多了。
猜你喜欢
  • 1970-01-01
  • 2013-06-09
  • 1970-01-01
  • 2012-07-09
  • 2010-09-25
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 2014-11-04
相关资源
最近更新 更多