Html 从同一个 onclick 调用两个函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16025138/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:34:39  来源:igfitidea点击:

Call two functions from same onclick

javascripthtmlonclick

提问by user182

HTML & JS

HTML & JS

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

如何从一个 onclick 事件调用 2 个函数?这是我的代码

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

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

这两个函数是 pay() 和 cls()。谢谢!

回答by Chris Bier

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

这是来自 SitePoint http://reference.sitepoint.com/html/event-attributes/onclick 的一个很好的参考

回答by Renan

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();"/>

回答by pollirrata

You can call the functions from inside another function

您可以从另一个函数内部调用这些函数

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

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

回答by Lucien Baron

With jQuery :

使用 jQuery :

jQuery("#btn").on("click",function(event){
    event.preventDefault();
    pay();
    cls();
});

回答by karaxuna

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

不推荐从 html 绑定事件。这是推荐的方式:

document.getElementById('btn').addEventListener('click', function(){
    pay();
    cls();
});

回答by elclanrs

Just to offer some variety, the comma operatorcan be used too but some might say "noooooo!", but it works:

只是为了提供一些多样性,也可以使用逗号运算符,但有些人可能会说“noooooo!”,但它有效:

<input type="button" onclick="one(), two(), three(), four()"/>

http://jsbin.com/oqizir/1/edit

http://jsbin.com/oqizir/1/edit

回答by Amine Hajyoussef

onclick="pay(); cls();"

however, if you're using a return statement in "pay" function the execution will stop and "cls" won't execute,

但是,如果您在“pay”函数中使用 return 语句,则执行将停止并且“cls”不会执行,

a workaround to this:

解决方法:

onclick="var temp = function1();function2(); return temp;"

回答by pk2218

put a semicolon between the two functions as statement terminator.

在两个函数之间放置一个分号作为语句终止符。

回答by Sachin

Try this

尝试这个

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