使用jquery为每个事件添加事件处理程序

Add event handler to each using jquery

本文关键字:添加 事件处理 程序 事件 jquery 使用      更新时间:2023-09-26

如何同时使用。on和。each ?

$('[id^="thing"]').each(???)

可以是:

 $("#button").on("click", function() {
                    console.log(this.id)
 })

在包含多个元素的jQuery对象上调用.on()将为每个元素添加处理程序。

$('[id^="thing"]').on("click", function() { });

你可以使用这个版本来指定一个选择器,来指定哪些子元素应该触发事件。

$('[id^="thing"]').on('click','button (or whatever selector)', function(){
  // "this" refers to triggering element
  alert($(this).text());
});

try

   $('[id^="thing"]').each(function(i, el) {
        $(el).on("click", function() {                 
       })
    });

不需要.each.on

你想做的事只能用这个-

一个好方法

$(document).on('click','[id^="thing"]', function() {
    console.log(this.id)
});

你可以这样做,但它会毫无理由地影响性能

你想要的方式,但要避免

$('[id^="thing"]').each(function(){
  $(this).on('click', function() {
    console.log(this.id)
  });
});

如果你在.each中使用.on,你可以
中以这种方式多次绑定事件

错误的方式

$('[id^="thing"]').each(function(){
  $('[id^="thing"]').on('click', function() {
    console.log(this.id)
  });
});