Nested jquery selectors that fire both parent and child events

I have a table with the following structure

  • table # Main
    • TBODY
      • tr.Row
        • td
          • input.EditRow

My jquery looks like this:

$("table#Main > tbody > tr.Row").live("click", function (e) { RowClick($(this)); }); $(".EditRow").live("click", function (e) { EditRow($(this)); }); 

My problem is that if I press the .EditRow button and call the EditRow function, the RowClick function will be called immediately.

After doing some research on the site, I saw that others circumvented this problem using one of the following commands.

 e.preventDefault(); e.stopPropagation(); 

I tried them on both functions in different combinations, but could not understand. Can someone tell me what I'm doing wrong?

Thanks! <3

+4
source share
2 answers

Update: As @patrick shows in his comment, event.stopPropagation() should work from jQuery 1.4.3 .


For jQuery 1.4.2 and below:

The problem is that both event handlers are bound to the root of the DOM tree due to .live() :

The handler passed to .live() is never associated with an element; instead .live() binds a special handler to the root of the DOM tree.

So event.stopPropagation no longer valid (both event handlers are on the same level):

Since the .live() method handles events when they propagate at the top of the document, it is not possible to stop the distribution of live events.

Use event.stopImmediatePropagation and change the binding order of the event handlers (otherwise it will not work with invoking the event handlers in the order that they bind):

 $(".EditRow").live("click", function (e) { e.stopImmediatePropagation(); EditRow($(this)); }); $("table#Main > tbody > tr.Row").live("click", function (e) { RowClick($(this)); }); 
+5
source
 $(".EditRow").live("click", function (e) { e.stopPropagation(); EditRow($(this)); }); 

It should work fine.

+1
source

Source: https://habr.com/ru/post/1335457/


All Articles