简体   繁体   中英

How can I isolate the initial target of a click, if the click event bubbles up to elements bound to the same click handler?

I'm working with a nested treeview menu, with 3 layers of nesting. Each list item (of each layer) is responsible for loading some new content onto the page when clicked:

$('li', '#navigation').click(function(event) { // this targets all three layers of nested menu items

    event.preventDefault(); // prevents click from making new server request

    var url = $("a", this).attr("href");

    loader.load(url);
});

The problem is, when you click a nested list item (one or two layers down), the "click" bubbles up through each list item above it, causing all three to run the specified event handler loader.load() method. In turn, clicking any nested list item loads the top-level list item's content.

So, when the event fires, I would like to check if what caused the event handler to execute was the originator of the click. Event.target (and anything that tells me about the current list item) will not work, as they tell me the currently firing item, rather than the originator.

Finally, event.stopPropogation() would not work, because it would stop propagation for all nested elements, as they are contained withing higher level elements.

Any ideas on how I can determine the originator of the click event?

UPDATE: Here is the JSFiddle: http://jsfiddle.net/kUR3r/

Just bind to the anchor, not the li . Why would you bind to the li in the first place?

$('#navigation').on('click', 'a', function(event) {
  event.preventDefault();

  var url = $(this).attr('href');

  // whatever else your code does
});

http://jsfiddle.net/kUR3r/3/

return false; seems to do the trick: http://jsfiddle.net/John_C/kUR3r/1/

    $('li', 'ul').click(function (event) {

        event.preventDefault();

        var url = $("a", this).attr("href");

        // loader.load(url);


        $('.target').text(url);
        return false;
    });

I think it's something have to do with your selector? $("a", this) will trigger all a tag. I might be wrong.

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