简体   繁体   中英

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

You can't execute two functions at the same time. JavaScript in a web browser is single threaded.

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

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

<div onclick="(function(){check_update('personal_details'); otherFunction(); })()">Click me </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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