采用以下代码:
// 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很糟糕。
答案 0 :(得分:20)
从jQuery 1.7开始,delegateTarget
属性包含在作为第一个参数给你的事件对象中,(according to the docs)给你:
当前调用的jQuery事件处理程序附加的元素。
所以请给出以下内容;
$("ul.hpList").on("click", "a.hpThumb", function (event) {
event.preventDefault();
var $this = $(this),
var $hpList = $(event.delegateTarget);
changeItem($this, $hpList);
});
答案 1 :(得分:1)
我不清楚你实际上想要找到什么,但是:
在处理程序中使用event.target来确定触发事件的实际DOM元素。
使用$(this)
来确定处理程序附加到哪个DOM元素,这可能是相同的事物,也可能是事件目标的父元素。
使用.closest()查找符合给定选择器的元素最近的祖先。
答案 2 :(得分:-1)
试试这个:
$("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);
});