简体   繁体   中英

jQuery Children selector question

I have the following code:

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

The Table1 html table has 2 columns; one for Names and one for a <button> element.

When I click on a table row, it works fine. When I click on the button, the button code fires; however, so does the row code.

How can I filter the selector so the button doesn't trigger the parent element's click event?

This is what you want.

It's stopPropogation that will stop the parents.

<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>

Here's a link to an example of it working as well:

http://jsbin.com/uyuwi

You can tinker with it at: http://jsbin.com/uyuwi/edit

You could also do something like this:

 $('#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; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <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>

Is it possible to remove the button code and just run the row code, therefore kind of using event bubbling.

Another couple options:

  • can you add a class to the TD that has the button in it and in the selector, do '[class!="className"]'
  • maybe try event.preventDefault() . You can see it being used here . this way you can prevent the default action that is triggered when the button is clicked, although I'm not sure if it will completely prevent the bubbling.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM