问题
I have a list of checkboxes inside a table with a simple jQuery function that allows the user to click anywhere in the table row to check/uncheck the checkbox. It works great, except when the user actually clicks on the checkbox. It doesn't work then. Any ideas? Here is my code:
HTML:
<tr onClick="checkBox()">...</tr>
jQuery:
function checkBox() {
var ischecked = $('input#myContacts').attr("checked");
if(ischecked)
{
$('input#myContacts').attr("checked", false);
}
else
{
$('input#myContacts').attr("checked", true);
}
return false;
}
回答1:
You can use event.stopPropagation to avoid your input#myContacts
's click event propagates to the tr
's click event. Also, I can't believe you are mixing jQuery and DOM in that way yet, when you should be using jQuery Events.
$(document).ready(function(){
$("input#myContacts").click(function(e){
e.stopPropagation();
});
});
回答2:
Without the HTML showing why that function is triggered by it's hard to say. A jsFiddle would be helpful. Just speculation, but could it be that you click the checkbox, which checks it, but the click event immediately calls that function which unchecks it?
回答3:
<tr class="checkBox">...</tr>
$(document).ready(function () {
$('tr.checkBox').live('click', function (e) {
if (e.target.type !== 'checkbox') {
$('input#myContacts').attr("checked", function () {
return !$(this).prop('checked');
});
//Or
$(this).find('input#myContacts').attr("checked", function () {
return !$(this).prop('checked');
});
}
});
});
回答4:
Solution 1: http://jsfiddle.net/qmdGK/3/ (Using two table cells but only binding click to text cell)
Solution 2: http://jsfiddle.net/qmdGK/4/ (using stopPropagation() on the checkbox click event)
Both are using jQuery to bind the event to the element which is preferred.
来源:https://stackoverflow.com/questions/10663432/how-do-i-prevent-default-checkbox-event-from-overriding-my-jquery-check-uncheck