简体   繁体   中英

Add event handler to each using jquery

How would I use .on and .each together?

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

A single one would be:

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

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

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

You can use this version to specify a selector, to specify which child elements should trigger the event.

$('[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() {                 
       })
    });

you don't need .each with .on ,

the thing you want can be done only with this -

A GOOD WAY

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

it can be done as you want it but as it will impact performance with no reason

THE WAY YOU WANT BUT TO BE AVOIDED

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

and if you will use .on inside .each you may
end up in binding the event multiple times in this way

The WRONG WAY

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM