我曾经有一个这样的按钮:
<input type="button" value="Save" onclick="SaveReleaseStage(this, 'Reassigned', 'ReleaseStage/ReassignProcess');" />
其中传递的“this”是按钮。一切都很顺利。
当我将其更改为:
<input type="button" value="Save" onclick="ShowConfirmation('Confirm', 'Some message...', function () { SaveReleaseStage(this, 'Reassigned', 'ReleaseStage/ReassignProcess'); });" />
“this”现在是 Window 对象,而不是按钮。
有没有办法将按钮传递给回调,而无需添加 ID 和使用 getElementById 或 jQuery?
最佳答案
因为它是一个没有绑定(bind)上下文的匿名函数,因此 this
默认为全局对象。在您的情况下,这将是窗口
。
在此处进一步阅读有关此
行为:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
更新:根据您的问题编辑,您可以传入对按钮的闭包引用:
<input type="button" value="Save" onclick="var self=this; ShowConfirmation('Confirm', 'Some message...', function () { SaveReleaseStage(self, 'Reassigned', 'ReleaseStage/ReassignProcess'); });" />
关于javascript - 如何将按钮传递给onclick中的匿名回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23921777/