[英]add change() event to an existing click() function without triggering the first event
I have a JQuery click()
function and I need to add the change()
event for another element (that must only trigger the change()
event). 我有一个JQuery click()
函数,我需要为另一个元素添加change()
事件(必须仅触发change()
事件)。
How can I combine it, but make this extra element only trigger one of the two events? 如何合并它,但使此额外元素仅触发两个事件之一?
$('body').on('click change', '.click-1, .click-2, :checkbox, .change', function()
I added the change event and the change class. 我添加了更改事件和更改类。 Also for the checkboxes, are they going to trigger the two events? 同样对于复选框,它们是否将触发两个事件? (could it be a problem?). (可能有问题吗?)。
Is there any way to make the element only trigger that event and not the click()
? 有什么方法可以使元素仅触发该事件,而不触发click()
?
I just need to find a way to not repeat the same code (50 lines) twice. 我只需要找到一种方法就不会重复相同的代码(50行)两次。
EDIT: Fix (thanks to @somethinghere): 编辑:修复(由于@somethinghere):
$('body').on('click change', '.click-1, .click-2, :checkbox, .change', function(event) {
if (event.type == 'click' && $(this).hasClass( 'change' )) {
event.preventDefault();
event.stopImmediatePropagation();
return;
}
// more code
});
A proper fix should be use click()
only for the buttons. 正确的解决方法应该仅对按钮使用click()
。
Simple, store the function and pass the function as a parameter twice: 简单,存储函数并将函数作为参数传递两次:
function yourfunctionname(e) {
...
}
$('body').on('click', '.click-1, .click-2', yourfunctionname)
.on('change', ':checkbox, .change', yourfunctionname);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.