将多个点击处理程序合并为一个 [英] Combine multiple click handlers into one

查看:72
本文介绍了将多个点击处理程序合并为一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有两个执行相同功能的点击处理程序:

Say I have two click handlers which perform the same functionality :

$('#div1').click(function(event) {  
alert('here');                              
});

$('#div2').click(function(event) {  
alert('here');                              
});

如何将这两个处理程序合而为一,而不是重复警报的调用?

How can I combine these two handlers into one instead of repeating the call to alert ?

类似的东西:

$('#div1').click.('#div2').click(function(event) {  
alert('here');                              
});

推荐答案

尝试一下:

$('#div1, #div2').click(function(event) {  
   alert('here');                              
});

此外,如果在公共父级中包含很多div元素,则可以利用事件委托并将单个处理程序附加到父级本身,就像这样:

Furthermore, if you have a lot of div elements, contained in a common parent, you may take benefit of event delegation and attach a single handler to the parent itself, like so:

$('.common-parent').on('click', 'div', function(event) {  
   ...                          
});

这篇关于将多个点击处理程序合并为一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆