简体   繁体   English

将按钮的实例传递给其onclick函数jquery

[英]Pass an instance of a button to its onclick function jquery

In my program I am changing the onclick behavior of my buttons as: 在我的程序中,我正在改变按钮的onclick行为:

          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. 我想传递function1()一个按钮的实例,因为有各种各样的按钮可能会不时访问这个函数1()点击它们并知道他们的父母是我的逻辑必须。

Is this possible? 这可能吗?

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

You can pass "this" to the function, then that parameter will be the button. 您可以将“this”传递给函数,然后该参数将是按钮。

function function1(myButton){
//do stuff
}

Alternatively, you can use jquery and an anonymous function 或者,您可以使用jquery和匿名函数

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

You can always pass the this context and use it 您始终可以传递this上下文并使用它

 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.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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