如何以编程方式读取 Javascript 事件
想象一下你有一个像这样的按钮:
<input name="myButton" type="button" value="button" onclick="return test();" >
其中测试函数如下:
function test(){
// do something
return true; // based on some logic return boolean
}
现在让我们说,我不知道为 onclick 事件设置了什么,并且在运行时我需要读取该函数或设置为 onclick 的任何代码并运行它。这是一个例子:
var btn = getElementById('myButton');
var btnOnClickFunc = btn.onclick;
if (btnOnClickFunc) {
// do something
}
我知道这不起作用,这实际上是我的问题。如何在运行时读取此示例中按钮的 onclick 事件?
这种情况的一个示例是稍后使用 jQuery 将 onclick 附加到按钮。
Imagine you have a button like this:
<input name="myButton" type="button" value="button" onclick="return test();" >
where the test functions is as follows:
function test(){
// do something
return true; // based on some logic return boolean
}
Now let's say,I don't know what is set for the onclick event, and at runtime I need to read the function or any code set to onclick and run it. Here is an example:
var btn = getElementById('myButton');
var btnOnClickFunc = btn.onclick;
if (btnOnClickFunc) {
// do something
}
I know this doesn't work, and that's actually my question. How can I read the button's onclick event in this example at runtime?
An example of this case is when the onclick is attached to the button later using jQuery.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您需要这样做,您可能希望最终重构您的代码,以便不再需要这样做。同时,您可以使用此技巧:
属性
'onclick'
实际上返回一个函数,因此使用()
调用它实际上会执行该函数。如果您不想使用 jQuery,则不必这样做。如果没有它,以下内容也可以工作:
此外,对于这两者中的任何一个,您都可以将其分成两行:
If you need to do this you might want to eventually refactor your code so that you no longer need to do this. In the meantime you can use this hack:
The attribute
'onclick'
actually returns a function, so calling it with()
actually executes that function.If you'd rather not use jQuery, you don't have to. The following works without it:
Also, for either of these two, you can break it up into two lines: