Getting the root element that a delegated event is bound to - jQuery

后端 未结 3 1601
孤街浪徒
孤街浪徒 2020-12-19 04:38

Taking the following code:

    // Bind the click event to the thumbnails.
    $(\"ul.hpList\").on(\"click\", \"a.hpThumb\", function (event) {

        event         


        
相关标签:
3条回答
  • 2020-12-19 04:47

    Since jQuery 1.7, the delegateTarget property is included in the event object given to you as the first parameter, which (according to the docs), gives you:

    The element where the currently-called jQuery event handler was attached.

    So give the following a go;

    $("ul.hpList").on("click", "a.hpThumb", function (event) {
        event.preventDefault();
    
        var $this = $(this),
        var $hpList = $(event.delegateTarget);
    
        changeItem($this, $hpList);
    });
    
    0 讨论(0)
  • 2020-12-19 04:57

    try this:

    $("ul.hpList").on("click", "a.hpThumb", function (event) {
        event.preventDefault();
        var $this = $(this),
        // Surely there has to be a smarter way to do this.
        $hpList = $("ul.hpList").has($this);
        changeItem($this, $hpList);
     });
    
    0 讨论(0)
  • 2020-12-19 05:01

    It's not clear to me what you're actually trying to find, but:

    Use event.target inside your handler to determine which actual DOM element triggered the event.

    Use $(this) to determine which DOM element the handler is attached to, which may be the same thing or may be a parent of the event target.

    Use .closest() to find an element's closest ancestor which fits a given selector.

    0 讨论(0)
提交回复
热议问题