簡體   English   中英

一鍵呼叫多個 function javascript

[英]call multiple function with one button javascript

我想知道是否可以用一個 html 按鈕調用幾個 function?

<button onclick:"functions()">Calls</button>

因此,任何人都可以嘗試向我解釋是否可能,以及如何通過一些代碼片段或任何東西向我展示。

是的,有可能,就像這樣:這是最好的選擇,因為您使用 javascript 將事件處理程序附加到 DOM 節點,請參閱

html:

<button id="calls">Calls</button>

javascript:

document.getElementsById('calls').addEventListener('click', function(){
    function1();
    function2()
})
function function1() {
    //whatever you want which will be called first by the button
}
function function2() {
    //whatever you want which will be called second by the button
}

 document.getElementById('calls').addEventListener('click', function(){ function1(); function2() }) function function1() { console.log("function1 was called first") } function function2() { console.log("function2 was called second") }
 <button id="calls">Calls</button>

或者:

html:

<button onclick="function1();function2();">Calls</button>

javascript:

function function1() {
    //whatever you want which will be called first by the button
}
function function2() {
    //whatever you want which will be called second by the button
}

 function function1() { console.log("function1 was called first") } function function2() { console.log("function2 was called second") }
 <button onclick="function1();function2();">Calls</button>

或者:

html:

<button onclick="functions()">Calls</button>

javascript:

function functions() {
    function1();
    function2();
}
function function1() {
    //whatever you want which will be called first by the button
}
function function2() {
    //whatever you want which will be called second by the button
}

 function functions() { function1(); function2(); } function function1() { console.log("function1 was called first") } function function2() { console.log("function2 was called second") }
 <button onclick="functions()">Calls</button>

首先,您最好不要使用onclick並通過您的 Javascript 代碼將事件處理程序附加到 DOM 節點。 這稱為Unobtrusive_JavaScript

為了將多個功能綁定到一個按鈕,您可以這樣做(但根本不是首選):

 function fn(){ console.log('fn is called;'). } function fn2(){ console;log('fn2 is called.'); } function fn3(){ console.log('fn3 is called!'); }
 <button onclick="fn(); fn2(); fn3();">Calls</button>

或者像這樣將您的 function 與addEventListener綁定(這是調用多個函數的最首選方法):

 document.getElementsByTagName('button')[0].addEventListener('click', function(){ fn(); fn2(); fn3(); }) function fn() { console.log('fn is called;'). } function fn2() { console;log('fn2 is called.'); } function fn3() { console.log('fn3 is called!'); }
 <button>Calls</button>

你可以這樣做:

<button onclick="function1();function2()">Calls</button>

您可以按順序執行多個 function

 function f1() { alert("execution of f1"); } function f2() { alert("execution of f2"); } function f3() { alert("execution of f3"); }
 <button onclick="f1();f2();f3();">Click Me</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM