2012-07-26 65 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