Pregunta

Suppose I have a nested table like the following:

<table id="search">
<tbody>
    <tr><td>a</td></tr>
    <tr><td>b</td></tr>  
   <tr><td>
       <table>
           <tr id="ex"><td>-----------</td></tr>           
        </table>
       </td>
   </tr>
       </tbody>

I want to bind a click event to the rows which are not in the nested table (so not to the row with ID "ex"). To clarify, I do not want anything at all to occur when I click on the excluded row. This seems like it should be easy, but I am having trouble with IE propagating events (I think).

JsFiddle: http://jsfiddle.net/9TWPx/1/

Here's what I've tried:

Base Case: Default behavior)

$("#search tr").click(function() {
alert($(this).closest("tr").index()); 
});

When clicking on the last row, this causes TWO alerts - firstly one containing the index 0, and then one containing the index 2.

Attempt #1)

$("#search tr").not("#ex").click(function() {
alert($(this).closest("tr").index());
});

This doesn't work - I no longer get the alert containing the 0 index, but I still get the alert containing the index 2 - which indicates to me that something must be bubbling up to the parent level (right?)

event.stopPropagation() doesn't seem to help - Attempt #2)

$("#search tr").not("#ex").click(function(event) {
event.stopPropagation();   
alert($(this).closest("tr").index());    
});

This causes me to get an alert with the index 2.

Attempt #3+)

I tried many different combinations of preventDefault(), stopBubble, stopPropogation etc and nothing seems to stop me from getting the alert with the index 2.

I realize this may have a simple answer, but please share it with me if you know!

Final edit: Turns out that this has nothing to do with event propagation, just to do with the fact that I missed that the row containing the nested table itself was getting the event bound to it, as well as the row inside the nested table.

¿Fue útil?

Solución

Just use

$("#search > tbody > tr:not(:has('table'))").click(function() {
    alert($(this).closest("tr").index());
});

Fiddle

Otros consejos

EDIT: Updated code -

$('#search tr').click(function (event) {
    event.stopPropagation();
    if ( this.id != "ex" ) {
        alert($(this).closest("tr").index());
    }
});

http://jsfiddle.net/jayblanchard/9TWPx/10/ (I also made sure your inner table was closed)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top