获取父级/祖先 UL
Get the parent/ancestor UL
>我有一个看起来像
<ul>
...
<li>
<ul class="x">
...
<a href="#"...
如何从挂钩在链接上的点击事件中获取父ul.x
元素?
如果 UL 是父元素,this.parentNode
工作,但如果它是祖先之一,我必须使用this.parentNode.parentNode
取决于中间有多少父元素......
我可以以某种方式获得第一个 UL 父级吗?
既然你已经把问题标记为jQuery:
$(this).closest("ul"); //Get the first ancestor `ul`
$(this).closest("ul.x"); //Get the first ancestor `ul` with class `x`
或者,没有jQuery(因为你的例子似乎没有使用jQuery):
var node = this;
while(node.tagName !== "UL") {
node = node.parentNode;
}
使用 closest()
. 这将获得与您提供的选择器匹配的最接近的祖先。
$(function(){
$('a').on('click',function(){ //handler of your <a>
var ulx = $(this).closest('ul.x'); //find the closest ancestor <ul> with class "x"
});
});
对于性能,
你也可以像下面这样使用jquery,jquery eventObject也有一个名为delegateTarget的属性,这对你来说可能很有用。
$('ul.x').on('click', 'a', function(e){
//e.delegateTarget is the parent ul of the clicked a tag
//e.target.id is the clicked a tag
alert(e.delegateTarget.id);
alert(e.target.id);
});
.HTML:
<ul id='a' class="x">
<li><a id='1' href="#">A</a></li>
<li><a id='2' href="#">B</a></li>
<li><a id='3' href="#">C</a></li>
</ul>
<ul id='b' class="x">
<li><a id='11' href="#">1</a></li>
<li><a id='21' href="#">2</a></li>
<li><a id='31' href="#">3</a></li>
</ul>
在性能方面,您不会在所有a
标记上绑定事件。 jQuery建议采用这种方式。
这是小提琴。
通常你会使用这样的.closest()
:
$('a').click(function(){
var ul = $(this).closest('ul.x'); //or just closest('ul') in case you only used the x for demo purposes
});
这将进入 DOM 树并在第一个匹配项(您的ul.x
-元素)处停止。
如果ul.x
是a
的直接父级,请使用以下命令:
$('a').on('click',function(){
var ul = $(this).parent('ul.x');
});
或
$('a').on('click',function(){
var ul = $(this).closest('ul.x');
});
相关文章:
- 在单独的ul's
- 将所选类别循环到ul>李用加载更多按钮
- 使用jquery动态创建ul-li
- 使用下拉列表筛选列表(ul>li)
- 如何附加<ul><李>元素位于某个特定条件的父元素列表之间
- :not选择器不适用于ul类-备选方案
- 在验证器中添加自定义规则以检查<ul>具有元素
- 在JQuery中隐藏和显示ul中的特定元素
- 使用 jquery 获取外部父 UL
- 隐藏/显示包含单词的ul li项目.但只能入住李的子女
- 如何在点击时显示ul项目
- 限制ul元素中显示的项目
- ul-li专属功能
- 将OnClick函数设置为<ul>,最后一个ul是擦除第一个ul-s
- 我应该如何在 UL 内触发 IMG 标签的点击
- 排序<李><Ul>根据<span>内部<李>
- jQuery(“ul.sf菜单”).superfish不是一个函数
- 在 ul 下更改内容的字体颜色,在悬停时
- 获取父级/祖先 UL
- Twitter Bootstrap 下拉菜单 - onclick 将“open”类放在祖先 ul 而不是子 ul 上