jQuery Children选择器问题

时间:2009-04-14 00:14:05

标签: javascript jquery

我有以下代码:

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

Table1 html表有2列;一个用于名称,一个用于<button>元素。

当我点击表格行时,它可以正常工作。当我点击按钮时,按钮代码触发;但是,行代码也是如此。

如何过滤选择器以使按钮不会触发父元素的点击事件?

3 个答案:

答案 0 :(得分: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

修改它

答案 1 :(得分: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;
        }

答案 2 :(得分:0)

是否可以删除按钮代码并运行行代码,因此可以使用事件冒泡。

另外几个选项:

  • 您可以在TD中添加一个类,其中包含按钮,并在选择器中执行'[class!="className"]'
  • 也许试试event.preventDefault()。你可以看到它是used here。通过这种方式,您可以阻止单击按钮时触发的默认操作,但我不确定它是否会完全阻止冒泡。
相关问题