繁体   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