简体   繁体   中英

Pass an instance of a button to its onclick function jquery

In my program I am changing the onclick behavior of my buttons as:

          button.attr('onclick','function1()');

I would like to pass function1() an instance of the button as there are a variety of buttons which may from time to time would access this function1() on clicking them and knowing their parents is a must for my logic.

Is this possible?

button.attr('onclick','function1(this);');

You can pass "this" to the function, then that parameter will be the button.

function function1(myButton){
//do stuff
}

Alternatively, you can use jquery and an anonymous function

$(button).click(function()
     {
         var myButton = this; // in this scope "this" is the button.
     });

You can always pass the this context and use it

 button.attr('onclick','function1(this)');

But why do you want to attach a inline event to you button. It is a better practice to attach the events directly.

button.on('click', someFunction);

function someFunction() {

   this

   // this corresponds to the button that is currently clicked.
}

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