javascript 通过一个 Click 事件调用多个函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9162349/
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
Call multiple functions from one Click event
提问by Enes Can ?etiner
i want call 2 actions but, if return false from first event, second will not run:
我想调用 2 个操作,但是,如果从第一个事件返回 false,则第二个将不会运行:
<input type = "button" name="Send" onClick="check();send();">
is it possible?
是否可以?
回答by KJ Tsanaktsidis
Can you do something like
你能做类似的事情吗
<input type="button" name="Send" onClick="if(check()){send();}">
回答by Anders Tornblad
You shouldn't put javascript inline like that.
您不应该像那样将 javascript 内联。
HTML:
HTML:
<html>
<head>
<script type="text/javascript" src="myJavascript.js"></script>
...more stuff in head...
</head>
<body>
<input type="button" name="Send" id="sendButton" />
</body>
</head>
myJavascript.js:
我的Javascript.js:
window.onload = function() {
document.getElementById("sendButton").onclick = function() {
if (check()) {
send();
}
};
};
This is extremely simplified, but will get you started in the right direction...
这是极其简化的,但会让你朝着正确的方向开始......
Also, you should look into using some javascript library to help with the "plumbing", like jQuery. It makes life a bit simpler...
此外,您应该考虑使用一些 javascript 库来帮助“管道”,例如 jQuery。它让生活变得更简单......
A smaller alternative to this:
一个较小的替代方案:
<script>
function check() {
// return true or false...
}
function send() {
// do stuff
}
function handleClick() {
if (check()) {
send();
}
}
</script>
<input type="button" name="Send" onclick="handleClick();" />
回答by Hyman
You can do:
你可以做:
<input type = "button" name="Send" onClick="myFun();">
Then in your code have:
然后在你的代码中有:
function myFun(){
check();
send();
}
回答by Eugene
The simplest way:
最简单的方法:
<script type="text/javascript">
function myfunc(){
if(check()) send();
}
</script>
And into HTML:
并进入 HTML:
<input type="button" onclick="myfunc();"/>