简体   繁体   English

如何在 onclick 事件中调用多个 JavaScript 函数?

[英]How to call multiple JavaScript functions in onclick event?

有没有办法使用onclick html 属性来调用多个 JavaScript 函数?

onclick="doSomething();doSomethingElse();"

But really, you're better off not using onclick at all and attaching the event handler to the DOM node through your Javascript code.但实际上,最好不要使用onclick并通过 Javascript 代码将事件处理程序附加到 DOM 节点。 This is known as unobtrusive javascript .这被称为不显眼的 javascript

A link with 1 function defined定义了 1 个函数的链接

<a href="#" onclick="someFunc()">Click me To fire some functions</a>

Firing multiple functions from someFunc()someFunc()触发多个函数

function someFunc() {
    showAlert();
    validate();
    anotherFunction();
    YetAnotherFunction();
}

This is the code required if you're using only JavaScript and not jQuery如果您只使用 JavaScript 而不是 jQuery,这是所需的代码

var el = document.getElementById("id");
el.addEventListener("click", function(){alert("click1 triggered")}, false);
el.addEventListener("click", function(){alert("click2 triggered")}, false);

Sure, simply bind multiple listeners to it.当然,只需将多个侦听器绑定到它。

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>

I would use the element.addEventListener method to link it to a function.我会使用element.addEventListener方法将它链接到一个函数。 From that function you can call multiple functions.您可以从该函数调用多个函数。

The advantage I see in binding an event to a single function and then calling multiple functions is that you can perform some error checking, have some if else statements so that some functions only get called if certain criteria are met.我看到将事件绑定到单个函数然后调用多个函数的优点是您可以执行一些错误检查,有一些 if else 语句,以便某些函数只有在满足某些条件时才会被调用。

ES6 React 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>

You can achieve/call one event with one or more methods.您可以使用一种或多种方法实现/调用一个事件。

One addition, for maintainable JavaScript is using a named function.另外,为了可维护的 JavaScript 是使用命名函数。

This is the example of the anonymous function:这是匿名函数的示例:

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

But imagine you have a couple of them attached to that same element and want to remove one of them.但是想象一下,你有几个连接到同一个元素并想要删除其中一个。 It is not possible to remove a single anonymous function from that event listener.无法从该事件侦听器中删除单个匿名函数。

Instead, you can use named functions:相反,您可以使用命名函数:

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

This also keeps your code a lot easier to read and maintain.这也使您的代码更易于阅读和维护。 Especially if your function is larger.特别是如果您的功能更大。

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

It's worked for me, you can call multiple functions in a single function.它对我有用,您可以在一个函数中调用多个函数。 then call that single function.然后调用该单个函数。

You can add multiple only by code even if you have the second onclick atribute in the html it gets ignored, and click2 triggered never gets printed, you could add one on action the mousedown but that is just an workaround.即使您在 html 中有第二个onclick属性,您也只能通过代码添加多个它被忽略,并且click2 triggered永远不会被打印,您可以在mousedown时添加一个,但这只是一种解决方法。

So the best to do is add them by code as in:所以最好的办法是通过代码添加它们,如下所示:

 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>

You need to take care as the events can pile up, and if you would add many events you can loose count of the order they are ran.您需要小心,因为事件可能会堆积起来,如果您要添加许多事件,您可能会丢失它们运行的​​顺序。

React Functional components反应功能组件

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

Here is another answer that attaches the click event to the DOM node in a .js file.这是另一个将点击事件附加到 .js 文件中的 DOM 节点的答案。 It has a function, callAll , that is used to call each function:它有一个函数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>

You can compose all the functions into one and call them.Libraries like Ramdajs has a function to compose multiple functions into one.您可以将所有函数组合为一个并调用它们。像Ramdajs这样的库具有将多个函数组合为一个的功能。

<a href="#" onclick="R.compose(fn1,fn2,fn3)()">Click me To fire some functions</a>

or you can put the composition as a seperate function in js file and call it或者您可以将组合作为单独的函数放在 js 文件中并调用它

const newFunction = R.compose(fn1,fn2,fn3);


<a href="#" onclick="newFunction()">Click me To fire some functions</a>

This is alternative of brad anser - you can use comma as follows这是brad anser的替代方法 - 您可以按如下方式使用逗号

onclick="funA(), funB(), ..."

however is better to NOT use this approach - for small projects you can use onclick only in case of one function calling (more: updated unobtrusive javascript ).但是最好不要使用这种方法 - 对于小型项目,您只能在一个函数调用的情况下使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM