当id被jquery更改时,通过id执行jquery函数

Execute jquery function by id when id is changed by jquery

本文关键字:jquery id 执行 通过 函数      更新时间:2023-09-26

可以使用以下功能更改html应答器的id:

$("#test").attr('id', 'test2');

我的示例代码是:

$("#test").click(function() {
    $("#test").attr('id', 'test2');
    alert('test');
    return false;
});
$("#test2").click(function() {
    $("#test2").attr('id', 'test');
    alert('test2');
    return false;
});

第一个函数工作正常,但当id更改时,第二个函数不运行。。。

你能帮我吗?

谢谢,

您需要使用事件委派:

$("body").on('click','#test2',function() {
 $("#test2").attr('id', 'test');
 alert('test2');
 return false;
});

事件处理程序绑定到元素本身,而不是像idclass这样的属性。因此,即使您更改了用于绑定事件的属性,处理程序也将保留在元素中。

因此,在我看来,最好通过条件检查来重用现有的处理程序。例如

$("#test").click(function () {
  if (this.id == "test") {
    alert('test');
    this.id = 'test2';
  } else {
    alert('test2');
    this.id = 'test';
  }
  return false;
});

无需将额外的处理程序绑定到另一个元素。这应该是:

  • 更快(无气泡延迟

  • 内存高效(较少的处理程序

    当谈到具有数百个元素的复杂CCD_ 3结构时。