JQuery切换复选框输入与表格单元格点击

时间:2014-06-03 10:41:30

标签: jquery checkbox

我想这样做,如果你点击表格单元格内的任何地方,单元格中的复选框将被切换。如果直接单击复选框,它也应该正常工作。

这里我使用红色边框空白“标签”作为可点击区域。理想情况下,我想避免使用标签。

http://jsfiddle.net/WPZf2/

<tr>
    <td><label><input type="checkbox"/></label></td>
    <td><input type="checkbox"/></td>
    <td><input type="checkbox"/></td>
</tr>   

此处正在检测表格单元格。

http://jsfiddle.net/WPZf2/1/

    $('td').click(function(){
        alert('click!');

如果返回false并单击复选框,则最初选中复选框,然后当您关闭警报弹出窗口时,复选框将再次清除。 (至少在Chrome,Firefox和IE11中)

http://jsfiddle.net/WPZf2/2/

    $('td').click(function(){
        alert('click!');
        return false;

我尝试了这个,返回false并且没有返回。如果单击它可以工作的单元格,但如果单击复选框则不起作用。

http://jsfiddle.net/WPZf2/3/

var $elem = $(this).find('input');
$elem.prop('checked', !$elem.prop('checked'));

如果我在没有return语句的情况下执行$ elem.click(),则会遇到同样的问题。

http://jsfiddle.net/WPZf2/4/

$elem.click();

如果我有“返回假”,它根本不起作用:

http://jsfiddle.net/WPZf2/5/

所以基本上我希望能够单击单元格中的任意位置,包括直接在复选框上切换复选框。

5 个答案:

答案 0 :(得分:8)

这是另一种替代方式。

$(function(){
   $('td').click(function (event) {
     if (!$(event.target).is('input')) {
        var obj =$(this).find('input');      
        obj.prop('checked', !obj.is(':checked'));      
       }
   });
});

<强> FIDDLE

答案 1 :(得分:2)

http://jsfiddle.net/WPZf2/18/

$('td').click(function(){
    $(this).find(':checkbox').click();
});

$(":checkbox").click(function(e) {
     e.stopPropagation();        
});

答案 2 :(得分:1)

试试这个

  

$(function(){
    $('td').click(function(){
        //alert('click!');
        var $elem = $(this).find('input');
        $elem.prop('checked', !$elem.prop('checked'));
        //$elem.click();
//        return false;
    });
    $('input[type="checkbox"]').click(function(){
        $(this).prop('checked',!$(this).prop('checked'));
    })
});

答案 3 :(得分:1)

试试这个:

$('td, input').click(function (event) { // add input in the selector
    event.stopPropagation(); // stop the event bubble up
    var tgl = !$(event.target).is('input') && 
              !$('input:checkbox:checked', this).length ? true : false;
     // above we checked if target is not input and checked input is 
     // not there initially
    $('input:checkbox', this).prop('checked', tgl);
});  //---------------------------------------^^^---passing the boolean value

Demo

答案 4 :(得分:0)

找到答案!

jQuery click on td to toggle checkbox

http://jsfiddle.net/WPZf2/6/

$('td').click(function (event) {
  if (!$(event.target).is('input')) {

      $('input:checkbox', this).prop('checked', function (i, value) {
         return !value;
      });
   }
相关问题