我使用的是 Jquery 1.7.2。
我想使用 Jquery 将 Html 元素横向移动到特定属性(id) 将鼠标悬停在我的页面中的任何 html 元素上。
我们有parents()函数,但问题是如何在具有id属性的父元素上选择停止$("*", document.body).click(function (e) {
e.stopPropagation();
var domEl = $(this).get(0);
var parentEls = $(domEl).parents()
.map(function () {
return this.tagName;
})
.get().join(", ");
$("b").append(""+ ParentEls + ""); });
这是代码,但我正在获取根之前的所有元素 但我想停止在标签中具有属性 id 的衣柜元素
请帮帮我。
最佳答案
只需使用 closest :
$(this).closest('#the-id');
<小时/>
除非您只是寻找具有任何 id 属性的最接近的一个,这将是:
$(this).closest('[id]');
<小时/>
编辑:看到您更新的问题后,这应该是您想要的:
$(document).click(function(e) {
e.preventDefault();
var parents = $(e.target).parentsUntil('[id]')
.map(function() { return this.tagName; }).get().join(',');
console.log(parents);
});
请注意,这种方法可以实现您想要的效果,无需选择点击事件并将其绑定(bind)到 DOM 中的每个节点,这是一种相当严厉的方法。
<小时/>编辑(再次):看起来您可能想包含带有 id 属性的标签(上面的解决方案是所有内容,但不包括该标签)。为此,解决方案非常相似:
$(document).click(function(e) {
e.preventDefault();
var $parents = $(e.target).parentsUntil('[id]');
var tagNames = $parents.add($parents.parent())
.map(function() { return this.tagName; }).get().join(',');
console.log(tagNames);
});
关于html - 使用 Jquery 横向 Html 元素直到特定属性 (id),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10538189/