获取委托事件绑定到的根元素-jQuery [英] Getting the root element that a delegated event is bound to - jQuery

查看:102
本文介绍了获取委托事件绑定到的根元素-jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

采用以下代码:

    // Bind the click event to the thumbnails.
    $("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 = $this.parents("ul.hpList");

        changeItem($this, $hpList);

    });

如何更好地确定事件绑定到的根祖先元素.在DOM上搜索此内容让我感觉很糟糕.

How do I better identify the root ancestor element that the event is bound to. I feel awful searching the DOM for this.

推荐答案

自jQuery 1.7起, 属性作为第一个参数包含在提供给您的事件对象中,该属性(文档),为您提供:

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:

已附加的当前调用的jQuery事件处理程序的元素.

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);
});

这篇关于获取委托事件绑定到的根元素-jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆