2009-04-14 67 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; 
     }