我可以在一个元素中有两个 JavaScript onclick 事件吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2881307/
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
Can I have two JavaScript onclick events in one element?
提问by Piyush
Can we put two JavaScript onclick events in one input type button tag? To call two different functions?
我们可以在一个输入类型按钮标签中放置两个 JavaScript onclick 事件吗?调用两个不同的函数?
回答by rochal
This one works:
这个有效:
<input type="button" value="test" onclick="alert('hey'); alert('ho');" />
<input type="button" value="test" onclick="alert('hey'); alert('ho');" />
And this one too:
还有这个:
function Hey()
{
alert('hey');
}
function Ho()
{
alert('ho');
}
.
.
<input type="button" value="test" onclick="Hey(); Ho();" />
So the answer is - yes you can :) However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.
所以答案是 - 是的,你可以 :) 但是,我建议使用不显眼的 JavaScript.. 将 js 与 HTML 混合只是令人讨厌。
回答by Sean Kinsey
The HTML
HTML
<a href="#" id="btn">click</a>
And the javascript
和 javascript
// get a cross-browser function for adding events, place this in [global] or somewhere you can access it
var on = (function(){
if (window.addEventListener) {
return function(target, type, listener){
target.addEventListener(type, listener, false);
};
}
else {
return function(object, sEvent, fpNotify){
object.attachEvent("on" + sEvent, fpNotify);
};
}
}());
// find the element
var el = document.getElementById("btn");
// add the first listener
on(el, "click", function(){
alert("foo");
});
// add the second listener
on(el, "click", function(){
alert("bar");
});
This will alert both 'foo' and 'bar' when clicked.
这将在单击时同时提醒 'foo' 和 'bar'。
回答by Jacob Relkin
You can attach a handler which would call as many others as you like:
您可以附加一个处理程序,它可以根据需要调用尽可能多的其他处理程序:
<a href="#blah" id="myLink"/>
<script type="text/javascript">
function myOtherFunction() {
//do stuff...
}
document.getElementById( 'myLink' ).onclick = function() {
//do stuff...
myOtherFunction();
};
</script>
回答by Luca Filosofi
There is no need to have two functions within one element, you need just one that calls the other two!
一个元素中不需要有两个函数,你只需要一个调用其他两个函数!
HTML
<a href="#" onclick="my_func()" >click</a>
JS
function my_func() {
my_func_1();
my_func_2();
}
回答by Elitmiar
You could try something like this as well
你也可以尝试这样的事情
<a href="#" onclick="one(); two();" >click</a>
<script type="text/javascript">
function one(){
alert('test');
}
function two(){
alert('test2');
}
</script>

