是否有任何方法使用onclick html属性调用多个JavaScript函数?
当前回答
功能组件
<Button
onClick={() => {
cancelAppointment();
handlerModal();
}}
>
Cancel
</Button>
其他回答
你可以只通过代码添加多个,即使你在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
您需要小心,因为事件可能会堆积起来,如果您要添加许多事件,您可能会记不清它们运行的顺序。
当然,只需将多个侦听器绑定到它。
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>
另外,为了便于维护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);
这也使您的代码更容易阅读和维护。特别是当函数更大的时候。
ES6反应
<MenuItem
onClick={() => {
this.props.toggleTheme();
this.handleMenuClose();
}}
>
const callDouble = () =>{
increaseHandler();
addToBasket();
}
<button onClick={callDouble} > Click </button>
这对我来说很有用,你可以在一个函数中调用多个函数。然后调用这个函数。
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- 创建圈div比使用图像更容易的方法?