一键调用多个函数javascript

Jea*_*ira -1 javascript button

我想知道是否可以用一个 html 按钮调用多个函数?

<button onclick:"functions()">Calls</button>
Run Code Online (Sandbox Code Playgroud)

因此,任何人都可以尝试向我解释是否可能以及如何通过一些代码片段或任何内容向我展示。

Woo*_*old 5

是的,这是可能的,就像这样:这是最好的选择,因为您使用 javascript 将事件处理程序附加到 DOM 节点,请参阅此

html:

<button id="calls">Calls</button>
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

<button id="calls">Calls</button>
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)

或者:

html:

<button onclick="function1();function2();">Calls</button>
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

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

或者:

html:

<button onclick="functions()">Calls</button>
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

<button onclick="function1();function2();">Calls</button>
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)