简体   繁体   中英

Pass argument through jquery event handler

I have the following code:

$(buttonID).on('click', onClickAddUpdate);

which calls onClickAddUpdate when button id is pressed. The thing is, can I pass a parameter into onClickAddUpdate? ie:

$(buttonID).on('click', onClickAddUpdate(i));

where i is the id of a div I want to access.

The remaining code is structured like this:

 var onClickAddUpdate;

 onClickAddUpdate = function(){

 /*add  paragraph element to div tag */
 }

Yes you can,

see http://api.jquery.com/on/

Section Passing data to the handler

Example:

$(buttonID).on('click', {i: '1'}, onClickAddUpdate );

Sure, you can, in this way (take a look at JQuery API ) :

var onClickAddUpdate = function(e) {
  console.log(e.data.i);
}

$(buttonID).on('click', {i: '1'}, onClickAddUpdate);

Test on this example .

Another way is:

var onClickAddUpdate = function(id) {
  console.log(id);
}

$(buttonID).on('click', function() {
    onClickAddUpdate(i);
});

Test on this example .

Of course, you can do it:

var onClickAddUpdate = function(e, id) {
     console.log(id);
}

$(buttonID).on('click', function(e) { onClickAddUpdate(e, $(this).attr('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