javascript 我们可以调用两个函数 onClick 事件吗
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10498621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
can we call two functions onClick event
提问by Shashi Roy
I am trying something like this
我正在尝试这样的事情
<div onclick="check_update('personal_details') ; showUser(2)">Click me </div>
but only check_update('personal_details')is getting called . I want to execute two separate functions at the same time when DIV is clicked. Any help will be great for me as I am still in a learning phase. Thanks in advance.
但只有check_update('personal_details')被调用。我想在单击 DIV 时同时执行两个单独的函数。由于我仍处于学习阶段,因此任何帮助对我来说都很棒。提前致谢。
回答by Quentin
You can't execute two functions at the same time. JavaScript in a web browser is single threaded.
您不能同时执行两个函数。Web 浏览器中的 JavaScript 是单线程的。
The code you have will execute the functions sequentially, providing that the first one doesn't throw an exception and terminate the execution.
您拥有的代码将按顺序执行函数,前提是第一个函数不会引发异常并终止执行。
If it does throw an exception then you should try to resolve that. As a brute force hack:
如果它确实抛出异常,那么您应该尝试解决该问题。作为一个蛮力黑客:
try {
check_update('personal_details') ;
} catch (e) {
alert("Oh no! An exception! " + e);
}
showUser(2);
… but preventing the error in the first place is, obviously, a better solution!
……但首先防止错误显然是一个更好的解决方案!
回答by Will Demaine
You're question is tagged as jQuery, so I'm going to assume you're using it. In that case, you shouldn't be using the onclick attribute at all. This would be the correct way to write the code from a jQuery perspective:
你的问题被标记为 jQuery,所以我假设你正在使用它。在这种情况下,您根本不应该使用 onclick 属性。这将是从 jQuery 角度编写代码的正确方法:
<div id="yourId">Click me</div>
<script type="text/javascript">
$('#yourId').click(function(e) {
e.preventDefault();
check_update('personal_details');
showUser(2);
});
</script>
回答by Elliot Bonneville
Use a function within a closure. Replace otherFunction
with the name of the second function you'd like to call and everything should work as expected.
在闭包中使用函数。替换otherFunction
为您要调用的第二个函数的名称,一切都应该按预期工作。
<div onclick="(function(){check_update('personal_details'); otherFunction(); })()">Click me </div>