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


当前回答

 const callDouble = () =>{
    increaseHandler();
    addToBasket();
}                
<button onClick={callDouble} > Click </button>

这对我来说很有用,你可以在一个函数中调用多个函数。然后调用这个函数。

其他回答

定义了一个函数的链接

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

功能组件

             <Button
                onClick={() => {
                  cancelAppointment();
                  handlerModal();
                }}
             >
                Cancel
             </Button>

另外,为了便于维护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);

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

您可以将所有函数组合成一个并调用它们。像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>