Call two functions from same onclick [duplicate]

2019-01-21 00:42发布

This question already has an answer here:

HTML & JS

How do I call 2 functions from one onclick event? Here's my code

 <input id ="btn" type="button" value="click" onclick="pay() cls()"/>

the two functions being pay() and cls(). Thanks!

9条回答
等我变得足够好
2楼-- · 2019-01-21 01:06

You can call the functions from inside another function

<input id ="btn" type="button" value="click" onclick="todo()"/>

function todo(){
pay(); cls();
}
查看更多
成全新的幸福
3楼-- · 2019-01-21 01:17

Add semi-colons ; to the end of the function calls in order for them both to work.

 <input id="btn" type="button" value="click" onclick="pay(); cls();"/>

I don't believe the last one is required but hey, might as well add it in for good measure.

Here is a good reference from SitePoint http://reference.sitepoint.com/html/event-attributes/onclick

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-01-21 01:19

Binding events from html is NOT recommended. This is recommended way:

document.getElementById('btn').addEventListener('click', function(){
    pay();
    cls();
});
查看更多
forever°为你锁心
5楼-- · 2019-01-21 01:20

You can create a single function that calls both of those, and then use it in the event.

function myFunction(){
    pay();
    cls();
}

And then, for the button:

<input id="btn" type="button" value="click" onclick="myFunction();"/>
查看更多
看我几分像从前
6楼-- · 2019-01-21 01:20

put a semicolon between the two functions as statement terminator.

查看更多
迷人小祖宗
7楼-- · 2019-01-21 01:21

With jQuery :

jQuery("#btn").on("click",function(event){
    event.preventDefault();
    pay();
    cls();
});
查看更多
登录 后发表回答