简体   繁体   中英

One event on several elements

I have this function:

function Any(){
  this.b1 = $("#but1")
  this.b2 = $('<div id="but2" />')
  this.func = function(){
     alert('hello')
  }
  this.b1.on('click',function(){
   this.func()
  })
  this.b2.on('click',function(){
   this.func()
  })


}

I want to do something like this:

(this.b1, this.b2).on('click',this.close)

You can use add()

this.b1.add(this.b2).on('click',this.close);

FIDDLE

I would keep an array of selectors:

//code
    this.selectors = ["#but1", "#but2"];
    $(this.selectors.join(",")).on('click', this.close);
//code
$("#but1,#but2").on("click",function(){
this.func();
});

Using the advanced syntax of .on() you may attach a listener to
a defined and stable object/selector (this) to look for the even on
dynamic SubComponents/selectors (#but1, #but2)
witch may or may not exists ... or show up later.

this.on('click','#but1,#but2',this.close);

Or in the more general case:

document.on('click','#but1,#but2', function(){ $('#my_dialog').close});

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