![](/img/trans.png)
[英]How to call multiple JavaScript functions by using function in onclick event and using loop to count functions from array in function?
[英]How to call multiple JavaScript functions in onclick event?
有沒有辦法使用onclick
html 屬性來調用多個 JavaScript 函數?
onclick="doSomething();doSomethingElse();"
但實際上,最好不要使用onclick
並通過 Javascript 代碼將事件處理程序附加到 DOM 節點。 這被稱為不顯眼的 javascript 。
定義了 1 個函數的鏈接
<a href="#" onclick="someFunc()">Click me To fire some functions</a>
從someFunc()
觸發多個函數
function someFunc() {
showAlert();
validate();
anotherFunction();
YetAnotherFunction();
}
如果您只使用 JavaScript 而不是 jQuery,這是所需的代碼
var el = document.getElementById("id");
el.addEventListener("click", function(){alert("click1 triggered")}, false);
el.addEventListener("click", function(){alert("click2 triggered")}, false);
當然,只需將多個偵聽器綁定到它。
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>
我會使用element.addEventListener
方法將它鏈接到一個函數。 您可以從該函數調用多個函數。
我看到將事件綁定到單個函數然后調用多個函數的優點是您可以執行一些錯誤檢查,有一些 if else 語句,以便某些函數只有在滿足某些條件時才會被調用。
ES6 反應
<MenuItem
onClick={() => {
this.props.toggleTheme();
this.handleMenuClose();
}}
>
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>
您可以使用一種或多種方法實現/調用一個事件。
另外,為了可維護的 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);
這也使您的代碼更易於閱讀和維護。 特別是如果您的功能更大。
const callDouble = () =>{
increaseHandler();
addToBasket();
}
<button onClick={callDouble} > Click </button>
它對我有用,您可以在一個函數中調用多個函數。 然后調用該單個函數。
即使您在 html 中有第二個onclick
屬性,您也只能通過代碼添加多個它被忽略,並且click2 triggered
永遠不會被打印,您可以在mousedown
時添加一個,但這只是一種解決方法。
所以最好的辦法是通過代碼添加它們,如下所示:
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>
您需要小心,因為事件可能會堆積起來,如果您要添加許多事件,您可能會丟失它們運行的順序。
反應功能組件
<Button
onClick={() => {
cancelAppointment();
handlerModal();
}}
>
Cancel
</Button>
這是另一個將點擊事件附加到 .js 文件中的 DOM 節點的答案。 它有一個函數callAll
,用於調用每個函數:
const btn = document.querySelector('.btn'); const callAll = (...fns) => (...args) => fns.forEach(fn => fn?.(...args)); function logHello() { console.log('hello'); } function logBye() { console.log('bye'); } btn.addEventListener('click', callAll(logHello, logBye) );
<button type="button" class="btn"> Click me </button>
您可以將所有函數組合為一個並調用它們。像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>
這是brad anser的替代方法 - 您可以按如下方式使用逗號
onclick="funA(), funB(), ..."
但是最好不要使用這種方法 - 對於小型項目,您只能在一個函數調用的情況下使用 onclick(更多:更新的不顯眼的 javascript )。
function funA() { console.log('A'); } function funB(clickedElement) { console.log('B: ' + clickedElement.innerText); } function funC(cilckEvent) { console.log('C: ' + cilckEvent.timeStamp); }
div {cursor:pointer}
<div onclick="funA(), funB(this), funC(event)">Click me</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.