是否有任何方法使用onclick html属性调用多个JavaScript函数?


当前回答

如果只使用JavaScript而不使用jQuery,则需要此代码

var el = document.getElementById("id");
el.addEventListener("click", function(){alert("click1 triggered")}, false);
el.addEventListener("click", function(){alert("click2 triggered")}, false);

其他回答

onclick="doSomething();doSomethingElse();"

但实际上,最好完全不使用onclick,而是通过Javascript代码将事件处理程序附加到DOM节点。这就是所谓的不显眼的javascript。

另外,为了便于维护JavaScript,可以使用命名函数。

下面是匿名函数的例子:

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') });

但是,想象一下,您有一对附加到同一个元素上的它们,并且想要删除其中一个。从该事件侦听器中删除单个匿名函数是不可能的。

相反,你可以使用命名函数:

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);

这也使您的代码更容易阅读和维护。特别是当函数更大的时候。

你可以只通过代码添加多个,即使你在html中有第二个onclick属性,它会被忽略,click2触发永远不会被打印,你可以添加一个鼠标下的动作,但这只是一个变通办法。

所以最好的方法是通过代码添加它们,如:

var element = document.getElementById("multiple_onclicks"); 元素。addEventListener("点击",function(){console.log("点击3触发")},false); 元素。addEventListener("点击",function(){console.log("点击4触发")},false); <button id="multiple_onclicks" onclick='console.log("click1触发");' onclick='console.log("click2触发");' onmousedown='console.log("click mousedown触发");' >点击我</button> .log

您需要小心,因为事件可能会堆积起来,如果您要添加许多事件,您可能会记不清它们运行的顺序。

var btn = document.querySelector('#twofuns'); btn.addEventListener(“点击”,method1); btn.addEventListener(“点击”,method2); 函数method2 () { console.log(方法2); } 函数method1 () { console.log(方法1); } <!DOCTYPE html > < html > < >头 < meta charset = " utf - 8 " > <meta name="viewport" content="width=device-width"> <标题> Pramod Kharade-Javascript < /名称> > < /头 身体< > <button id="twofuns">点击我!< /按钮> 身体< / > < / html >

您可以使用一个或多个方法实现/调用一个事件。

您可以将所有函数组合成一个并调用它们。像Ramdajs这样的库具有将多个函数组合成一个函数的功能。

<a href="#" onclick="R.compose(fn1,fn2,fn3)()">Click me To fire some functions</a>

或者你可以把合成作为一个单独的函数在js文件中调用它

const newFunction = R.compose(fn1,fn2,fn3);


<a href="#" onclick="newFunction()">Click me To fire some functions</a>