简体   繁体   English

我们可以调用两个函数onClick事件

[英]can we call two functions onClick event

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 . 但只有check_update('personal_details')被调用。 I want to execute two separate functions at the same time when DIV is clicked. 我想在单击DIV的同时执行两个单独的功能。 Any help will be great for me as I am still in a learning phase. 任何帮助对我来说都很棒,因为我还处于学习阶段。 Thanks in advance. 提前致谢。

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! ...但是,首先防止错误显然是更好的解决方案!

You're question is tagged as jQuery, so I'm going to assume you're using it. 你的问题被标记为jQuery,所以我假设你正在使用它。 In that case, you shouldn't be using the onclick attribute at all. 在这种情况下,您根本不应该使用onclick属性。 This would be the correct way to write the code from a jQuery perspective: 这将是从jQuery透视图编写代码的正确方法:

<div id="yourId">Click me</div>

<script type="text/javascript">
$('#yourId').click(function(e) {
    e.preventDefault();
    check_update('personal_details'); 
    showUser(2);
});
</script>

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>

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

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