2012-07-26 63 views
0

我正在使用jQuery的事件委托向表行添加单击事件。我在该行的第一个td中也有一个复选框。当我点击行中的任何地方时,一切都按预期工作。不过,当我点击复选框时,我不希望事件发挥作用。我试过使用:not()选择器,但也许我错过了一些东西,因为当我单击复选框时,仍然触发事件。如何忽略td内的复选框


HTML

<tr> 
    <td> 
     <div class="myCheckbox"><input type="checkbox" name="userName" /></div> 
    </td> 
    <td><a href="/go/to/user/profile"></a></td> 
    <td>more info</td> 
    <td>more info</td> 
    <td>more info</td> 
</tr> 

jQuery的

$('table tr:not(':checkbox')').on('click', 'td', function(event) { 

    // Do something 
}); 



我可以帮助解决我正在尝试做的事吗?

+0

[父事件处理程序的执行防止]的可能重复(http://stackoverflow.com/questions/1398582/prevent-execution-of-parent-event-handler) – 2012-07-26 21:22:22

回答

6

两个选项(包括涉及从现有的代码,就像你说的不工作  — tr元素不能复选框,并:not检查元素去掉tr:not的东西,而不是其内容):

  1. 将事件处理程序添加到调用e.stopPropagation的复选框。然后,点击事件将不会到达该行。你可以直接或通过授权来做到这一点。 Here's a live example直接。如果你是间接的,一定要点击label s激活复选框(如果你打算拥有它们)在你打算支持的所有浏览器上。

  2. 添加到您的处理程序:

    if ($(event.target).is('input[type=checkbox]')) { 
        return; 
    } 
    

    如:

    $('table').on('click', 'td', function(event) { 
    
        if ($(event.target).is('input[type=checkbox]')) { 
         return; 
        } 
    
        // Logic here 
    }); 
    

    即通过检测事件的源代码,看看它是否是一个复选框的作品,与脱困早。

在这两种情况下,如果你使用一个label激活复选框,你可能需要做同样的事情的标签。

我好奇会是什么样#2像处理label s,而事实证明它是足够的代码进入一个功能,但不硬  & MDASH可能我怎么会去:Live example | source

jQuery(function($) { 

    // The table cell click handler 
    $("table").on("click", "td", function(e) { 
    // Is the source a checkbox or the label for 
    // one? 
    if (isCheckbox($(e.target))) { 
     return; 
    } 

    // Normal handling 
    $(this).toggleClass("foo"); 
    }); 

    // Function to test whether the source is a 
    // checkbox, or the label of a checkbox 
    function isCheckbox($elm) { 
    var chkid; 

    if ($elm.is("input[type=checkbox]")) { 
     return true; 
    } 
    if ($elm.is("label")) { 
     chkid = $elm.attr("for"); 
     if (chkid) { 
     return $("#" + chkid).is("input[type=checkbox]"); 
     } 
     return !!$elm.find("input[type=checkbox]")[0]; 
    } 
    return false; 
    } 

}); 
+0

这是完美!非常感谢你。 – JsusSalv 2012-07-27 00:10:23

+0

优秀,T.J.!谢谢。 – JsusSalv 2012-07-27 00:32:18

0

尝试使用stopPropagation()来防止事件冒泡。

$('div.myCheckbox input[type=checkbox]').bind('change', function(e) { 
    e.stopPropagation(); 

    //do stuff here 
}); 
+1

“change”事件与表格单元格上的点击无关。 – 2012-07-26 21:30:56