2009-04-14 53 views
4

我有以下代碼:jQuery的孩子選擇問題

$("#Table1 tbody").children().each(function(e){ 
$(this).bind('click', 
      function(){ 
       // Do something here 
      }, 
      false) 
}); 

的表1 HTML表中有2列;一個用於名稱,另一個用於<button>元素。

當我點擊表格行時,它工作正常。當我點擊按鈕時,按鈕代碼被觸發;但是,行代碼也是如此。

如何過濾選擇器,使按鈕不觸發父元素的單擊事件?

回答

7

這就是你想要的。

這是stopPropogation這將阻止父母。

<table> 
    <tr> 
    <td>The TD: <input type="button" id="anotherThing" value="dothis"></td> 
    </tr> 
</table> 

<div id="results"> 
    Results: 
</div> 

<script> 

    $(function() { 
    $('#anotherThing').click(function(event) { 
     $('#results').append('button clicked<br>'); 
     event.stopPropagation();  
    }); 
    $('td').click(function() { 
     $('#results').append('td clicked<br>'); 

    }); 
    }); 

</script> 

下面是它的一個例子一個環節的工作,以及:

http://jsbin.com/uyuwi

你可以用它修補:http://jsbin.com/uyuwi/edit

0

是否有可能刪除按鈕代碼,只是運行行代碼,因此使用事件冒泡。

另外一對夫婦選擇:

  • 可以在類添加到在它和選擇按鈕的TD,做'[class!="className"]'
  • 也許嘗試event.preventDefault()。你可以看到它是used here。通過這種方式,您可以防止單擊按鈕時觸發的默認操作,儘管我不確定它是否會完全防止冒泡。
+0

最終,點擊上的行是選擇操作,而按鈕的onclick是刪除操作。我一直無法找出做這種作品的好方法。 – JamesEggers 2009-04-14 00:24:28

2

你也可以做這樣的事情:

<table id="Table1"> 
     <tbody> 
      <tr id="tr1"> 
       <td> 
        The TD: <input type="button" id="button1" value="dothis"/> 
       </td> 
      </tr> 
      <tr id="tr2"> 
       <td> 
        The TD: <input type="button" id="Button2" value="dothis"/> 
       </td> 
      </tr> 
     </tbody> 
    </table> 

支持JS

 $('#Table1 tr').bind('click', function(ev) { return rowClick($(this), ev); }); //Bind the tr click 
     $('#Table1 input').bind('click', function(ev) { return buttonClick($(this), ev); }) //Bind the button clicks 

     function rowClick(item, ev) { 
      alert(item.attr('id')); 
      return true; 
     } 

     function buttonClick(item, ev) { 
      alert(item.attr('id')); 
      ev.stopPropagation(); 

      return true; 
     }