Question

I have a table with a class "myClass" on each row that triggers a jQuery function by click on the table row.

This works fine so far, the only problem I have is that some of the table cells contain buttons and then a click on a button also triggers the above event.

Is there a way I can prevent that the row click event is triggered when I click on a button in that row ? I only want the event to fire by click on the row background but not by click on any button within a row.

Many thanks for any help with this, Tim.

Était-ce utile?

La solution

At the top of your click event handler, put the following:

if ($(event.target).prop('type').toLowerCase() !== 'table' ||
    ! $(event.target).hasClass('myClass')) {
    event.stopImmediatePropagation();
    return;
}

What this does is say 'if the actual element isn't a table or doesn't have the class "myClass" then stop the event here and now (the return part). The stopImmediatePropagation() means that it won't propagate back up to the original selector (your 'table.myClass' in this case).

If you want the user to be able to click on ANYTHING inside your table except buttons, you would use this:

if ($(event.target).prop('type').toLowerCase() === 'button') {
    event.stopImmediatePropagation();
    return;
}

This will allow clicks on other elements like inputs, images, spans, divs, etc. to still trigger it. If this is not the desired behavior, you should consider putting your click event on the table cells instead of the entire table, and then just check that the target type isn't a td.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top