如何在 onclick 事件中调用多个 JavaScript 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3910736/
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
How to call multiple JavaScript functions in onclick event?
提问by Qcom
Is there any way to use the onclick
html attribute to call more than one JavaScript function?
有没有什么办法可以使用onclick
html 属性来调用多个 JavaScript 函数?
回答by brad
onclick="doSomething();doSomethingElse();"
But really, you're better off not using onclick
at all and attaching the event handler to the DOM node through your Javascript code. This is known as unobtrusive javascript.
但实际上,您最好根本不使用onclick
并通过您的 Javascript 代码将事件处理程序附加到 DOM 节点。这被称为不显眼的 javascript。
回答by Marko
A link with 1 function defined
定义了 1 个函数的链接
<a href="#" onclick="someFunc()">Click me To fire some functions</a>
Firing multiple functions from someFunc()
触发多个函数 someFunc()
function someFunc() {
showAlert();
validate();
anotherFunction();
YetAnotherFunction();
}
回答by anandharshan
This is the code required if you're using only JavaScript and not jQuery
如果您仅使用 JavaScript 而不是 jQuery,则这是所需的代码
var el = document.getElementById("id");
el.addEventListener("click", function(){alert("click1 triggered")}, false);
el.addEventListener("click", function(){alert("click2 triggered")}, false);
回答by Girish Dusane
I would use the element.addEventListener
method to link it to a function. From that function you can call multiple functions.
我会使用该element.addEventListener
方法将其链接到一个函数。您可以从该函数调用多个函数。
The advantage I see in binding an event to a single function and then calling multiple functions is that you can perform some error checking, have some if else statements so that some functions only get called if certain criteria are met.
我认为将事件绑定到单个函数然后调用多个函数的优点是您可以执行一些错误检查,有一些 if else 语句,以便某些函数仅在满足某些条件时才被调用。
回答by Josh K
Sure, simply bind multiple listeners to it.
当然,只需将多个侦听器绑定到它即可。
Short cutting with jQuery
Short cutting with jQuery
$("#id").bind("click", function() {
alert("Event 1");
});
$(".foo").bind("click", function() {
alert("Foo class");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo" id="id">Click</div>
回答by Hitesh Sahu
ES6 React
ES6 反应
<MenuItem
onClick={() => {
this.props.toggleTheme();
this.handleMenuClose();
}}
>
回答by Pramod Kharade
var btn = document.querySelector('#twofuns');
btn.addEventListener('click',method1);
btn.addEventListener('click',method2);
function method2(){
console.log("Method 2");
}
function method1(){
console.log("Method 1");
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Pramod Kharade-Javascript</title>
</head>
<body>
<button id="twofuns">Click Me!</button>
</body>
</html>
You can achieve/call one event with one or more methods.
您可以使用一种或多种方法实现/调用一个事件。
回答by Eduard Florinescu
You can add multiple only by code even if you have the second onclick
atribute in the html it gets ignored, and click2 triggered
never gets printed, you could add one on action the mousedown
but that is just an workaround.
您只能通过代码添加多个,即使您onclick
在 html 中有第二个属性,它会被忽略,并且click2 triggered
永远不会被打印,您可以在 action 上添加一个,mousedown
但这只是一种解决方法。
So the best to do is add them by code as in:
所以最好的办法是通过代码添加它们,如下所示:
var element = document.getElementById("multiple_onclicks");
element.addEventListener("click", function(){console.log("click3 triggered")}, false);
element.addEventListener("click", function(){console.log("click4 triggered")}, false);
<button id="multiple_onclicks" onclick='console.log("click1 triggered");' onclick='console.log("click2 triggered");' onmousedown='console.log("click mousedown triggered");' > Click me</button>
You need to take care as the events can pile up, and if you would add many events you can loose count of the order they are ran.
您需要小心,因为事件可能会堆积如山,如果您要添加许多事件,您可以计算它们运行的顺序。
回答by Remi
One addition, for maintainable JavaScript is using a named function.
另外,对于可维护的 JavaScript,使用命名函数。
This is the example of the anonymous function:
这是匿名函数的示例:
var el = document.getElementById('id');
// example using an anonymous function (not recommended):
el.addEventListener('click', function() { alert('hello world'); });
el.addEventListener('click', function() { alert('another event') });
But imagine you have a couple of them attached to that same element and want to remove one of them. It is not possible to remove a single anonymous function from that event listener.
但是想象一下,你有几个附加到同一个元素上,并想删除其中一个。无法从该事件侦听器中删除单个匿名函数。
Instead, you can use named functions:
相反,您可以使用命名函数:
var el = document.getElementById('id');
// create named functions:
function alertFirst() { alert('hello world'); };
function alertSecond() { alert('hello world'); };
// assign functions to the event listeners (recommended):
el.addEventListener('click', alertFirst);
el.addEventListener('click', alertSecond);
// then you could remove either one of the functions using:
el.removeEventListener('click', alertFirst);
This also keeps your code a lot easier to read and maintain. Especially if your function is larger.
这也使您的代码更易于阅读和维护。特别是如果您的功能更大。
回答by user93
You can compose all the functions into one and call them.Libraries like Ramdajshas a function to compose multiple functions into one.
你可以将所有的函数组合成一个并调用它们。像Ramdajs这样的库有一个将多个函数组合成一个的功能。
<a href="#" onclick="R.compose(fn1,fn2,fn3)()">Click me To fire some functions</a>
or you can put the composition as a seperate function in js file and call it
或者您可以将组合作为单独的函数放在 js 文件中并调用它
const newFunction = R.compose(fn1,fn2,fn3);
<a href="#" onclick="newFunction()">Click me To fire some functions</a>