Click a div to check / uncheck a checkbox

匿名 (未验证) 提交于 2019-12-03 01:29:01

问题:

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?



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!