jQuery:禁用复选框上的“单击"事件 [英] Jquery: disable the 'click' event on a checkbox
问题描述
在当前的JQuery中,我有一个事件,如果用户单击表中的一行,该事件将选中或取消选中复选框.这样做的问题是,如果用户实际选中了复选框,则将在复选框事件上触发jquery,然后选中/取消选中该复选框,但是TR事件将触发,然后撤消该复选框的值.
In my current JQuery, I have an event that will either check or uncheck a checkbox if the user clicks on a row in a table. The problem with this is, if the user actually checks the checkbox, the jquery will fire on the checkbox event and either check/uncheck the box, but then the TR event will fire and then undo the checkbox value.
在此处查看示例: http://jsfiddle.net/radi8/KYvCB/1/
我可以禁用该复选框,但是如果用户尝试选择该复选框,则TR事件将不会触发.
I can disable the checkbox but then if the user tries to select the checkbox, the TR event will not trigger.
我需要的是一种禁用复选框的'click'事件,但仍允许在选中该复选框时触发TR事件的方法.
What I need is a method to disable the 'click' event of the checkbox but still allow the TR event to fire when the checkbox is selected.
var charges = {
init: function() {
// get the selected row checkbox
//$('.charges').attr('disabled', true);
$('.rowclick tr').click(function() {
if ($(this).find('td input.charges:checkbox').is(':checked')) {
$(this).find('td input.charges:checkbox').attr("checked", false);
}
else {
$(this).find('td input.charges:checkbox').attr("checked", true);
}
});
}
};
charges.init();
推荐答案
您需要检查click
事件是否在checkbox
或其他地方触发. 与使用e.stopPropagation
的复选框的第二个事件处理程序相比,此资源需要较少的资源.
You need to check if the click
event was fired on a checkbox
or somewhere else. This needs less ressources than a second event handler for the checkbox with e.stopPropagation
.
$('.rowclick tr').click(function(e) {
if($(e.target).closest('input[type="checkbox"]').length > 0){
//Chechbox clicked
}else{
//Clicked somewhere else (-> your code)
if ($(this).find('td input.charges:checkbox').is(':checked')) {
$(this).find('td input.charges:checkbox').attr("checked", false);
}
else {
$(this).find('td input.charges:checkbox').attr("checked", true);
}
}
});
工作示例: http://jsfiddle.net/KYvCB/5/
这篇关于jQuery:禁用复选框上的“单击"事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!