可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I applied the following code to make table rows check/uncheck a child checkbox when clicked. Now I discovered that when clicking the checkbox itself inside the row it doesent check. Could it be that it checks on click (standard function) and then the jquery picks up the click event and unchecks it? How can I fix this?
//check on div click $("tr").live("click",function() { var checkbox = $(this).find("input[type='checkbox']"); if( checkbox.attr("checked") == "" ){ checkbox.attr("checked","true"); } else { checkbox.attr("checked",""); } });
回答1:
I suspect that the click event is bubbling from the checkbox to the tr. Try adding this code as well:
$('tr input[type=checkbox]').click(function(e){ e.stopPropagation(); });
EDIT
here's an example: http://jsfiddle.net/GSqNv/
回答2:
Check the target of the caller is not a checkbox
$("tr").live("click",function(event) { var target = $(event.target); if (target.is('input:checkbox')) return; var checkbox = $(this).find("input[type='checkbox']"); if( checkbox.attr("checked") == "" ){ checkbox.attr("checked","true"); } else { checkbox.attr("checked",""); } });
DEMO http://jsfiddle.net/7Bze7/
The code above checks that the sender of the event is not a checkbox.
回答3:
Besides the given solutions, isn't it better to just set the checkbox to the oposite state? For example:
var _current_state = checkbox.attr("checked"); checkbox.attr("checked") = !_current_state;
回答4:
What about:
return false;
As it is the same as entering both:
e.preventDefault(); e.stopPropagation();
I believe that is the go to - no?