是否有任何方法使用onclick html属性调用多个JavaScript函数?
当前回答
你可以只通过代码添加多个,即使你在html中有第二个onclick属性,它会被忽略,click2触发永远不会被打印,你可以添加一个鼠标下的动作,但这只是一个变通办法。
所以最好的方法是通过代码添加它们,如:
var element = document.getElementById("multiple_onclicks"); 元素。addEventListener("点击",function(){console.log("点击3触发")},false); 元素。addEventListener("点击",function(){console.log("点击4触发")},false); <button id="multiple_onclicks" onclick='console.log("click1触发");' onclick='console.log("click2触发");' onmousedown='console.log("click mousedown触发");' >点击我</button> .log
您需要小心,因为事件可能会堆积起来,如果您要添加许多事件,您可能会记不清它们运行的顺序。
其他回答
我会用元素。addEventListener方法将其链接到函数。从该函数可以调用多个函数。
我认为将一个事件绑定到一个函数,然后调用多个函数的好处是,你可以执行一些错误检查,有一些if else语句,这样一些函数只在满足某些条件时才会被调用。
定义了一个函数的链接
<a href="#" onclick="someFunc()">Click me To fire some functions</a>
从someFunc()触发多个函数
function someFunc() {
showAlert();
validate();
anotherFunction();
YetAnotherFunction();
}
下面是另一个答案,它将单击事件附加到.js文件中的DOM节点。它有一个函数callAll,用于调用每个函数:
const btn = document.querySelector('.btn'); const callAll = (fn) = > (……args) = > fn。forEach(fn => fn?.(…args)); 函数logHello() { console.log('你好'); } 函数logBye() { console.log('再见'); } btn.addEventListener(“点击”, callAll (logHello logBye) ); <button type="button" class="btn"> 点击我 < /按钮>
const callDouble = () =>{
increaseHandler();
addToBasket();
}
<button onClick={callDouble} > Click </button>
这对我来说很有用,你可以在一个函数中调用多个函数。然后调用这个函数。
ES6反应
<MenuItem
onClick={() => {
this.props.toggleTheme();
this.handleMenuClose();
}}
>
推荐文章
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- 防止滚动条增加到Chrome页面的宽度
- 使用图像而不是单选按钮
- jQuery UI对话框-缺少关闭图标
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 我可以嵌套一个<按钮>元素内< >使用HTML5?
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?
- 设置TextView文本从html格式的字符串资源在XML
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误