是否有任何方法使用onclick html属性调用多个JavaScript函数?
当前回答
另外,为了便于维护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);
这也使您的代码更容易阅读和维护。特别是当函数更大的时候。
其他回答
我会用元素。addEventListener方法将其链接到函数。从该函数可以调用多个函数。
我认为将一个事件绑定到一个函数,然后调用多个函数的好处是,你可以执行一些错误检查,有一些if else语句,这样一些函数只在满足某些条件时才会被调用。
当然,只需将多个侦听器绑定到它。
jQuery速成
$(“#id”).bind(“click”, function() { 警报(“事件 1”); }); $(“.foo”).bind(“click”, function() { 警报(“Foo 类”); }); <script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js”></script> <div class=“foo” id=“id”>Click</div>
const callDouble = () =>{
increaseHandler();
addToBasket();
}
<button onClick={callDouble} > Click </button>
这对我来说很有用,你可以在一个函数中调用多个函数。然后调用这个函数。
功能组件
<Button
onClick={() => {
cancelAppointment();
handlerModal();
}}
>
Cancel
</Button>
ES6反应
<MenuItem
onClick={() => {
this.props.toggleTheme();
this.handleMenuClose();
}}
>
推荐文章
- 将lodash导入到angular + typescript应用程序中
- 什么时候使用setAttribute vs .attribute=在JavaScript?
- 每60秒调用一个函数
- 如何隐藏元素而不让他们在页面上占用空间?
- 我如何链接到谷歌地图与特定的经度和纬度?
- 我如何上传一个文件与JS获取API?
- 在JavaScript中是否有一个“not in”操作符来检查对象属性?
- 防止跨度元件断行
- 我如何能得到滚动条的位置与JavaScript?
- JavaScript中的yield关键字是什么?
- 如何显示一个对象的所有方法?
- 如何防止滚动条重新定位网页?
- .js和.mjs文件有什么区别?
- Axios处理错误
- ESLint解析错误:意外的令牌