Jquery第一次出现树遍历父母/兄弟姐妹
给定一个类最接近(树上)的最佳方法是什么,但它可以是父级的兄弟姐妹。
我想让“errors1”元素以元素“.start”开头
<div>
...
<div class="errors">errors2</div>
<div>
.....
<div class="errors">errors1</div>
...
<div>...</div>
<div>
.....
<div class="start"></div>
</div>
</div>
</div>
制作了一个脚本,但它真的很糟糕并且根本不起作用。
谢谢
编辑: 添加“...”以增强结构的动态性。重点是找到树上最接近的“.errors”。
What is the best way to get closest (up tree) given a class, but it can be a sibling of a parent.
I want to get "errors1" element start with element ".start"
<div>
...
<div class="errors">errors2</div>
<div>
.....
<div class="errors">errors1</div>
...
<div>...</div>
<div>
.....
<div class="start"></div>
</div>
</div>
</div>
Made a script but its really bad and doesnt work at all.
Thanks
EDITED:
Added "..." to enhance that structure is dynamic. The point is to find the closest ".errors" up tree.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
很好的问题。下面的代码应该适合你。它循环遍历
.start
的每个父元素,直到找到带有.errors
的元素。然后,它会警告最接近.start
的.errors
元素的文本。Great question. The code below should work for you. It loops over each parent of
.start
until it finds an element with.errors
. Then it alerts the text of the.errors
element that is closest to.start
.研究 jQuery 的
prev()
命令。例如,要在“start”类的上下文中查找并隐藏以前的“错误”,您可以使用以下内容:在此处阅读更多信息:http://api.jquery.com/prev/
更新:
使用
parent()
进行遍历可能会有更好的运气如果嵌套很重,则向上。parent()
还接受一个选择器作为参数...如果没有参数,它会获取当前节点的父节点。http://api.jquery.com/parent/
Investigate jQuery's
prev()
command. For example, to find and hide the previous 'errors' when in the context of the 'start' class, you would use the following:Read more here: http://api.jquery.com/prev/
UPDATE:
You may have better luck using
parent()
to traverse upward if it is heavily nested.parent()
also takes a selector as an argument... without an argument it grabs the parent of the current node.http://api.jquery.com/parent/
一个将项目作为 jQuery 对象返回的函数,因此它更可重用。
这比 Byran 的答案更有效,因为它一次只查看一个级别,而不是加载所有父级并通过 find (http://api.jquery.com/find/) 每次。
要使用该函数,只需在加载 jQuery 后将该函数粘贴到 javascript 文件或脚本标记中即可。
A function to return the item as a jQuery object so it is more reusable.
This is more efficient than Byran's answer because it only looks at one level at a time rather than loading all parents and checking all levels of children via find (http://api.jquery.com/find/) each time.
To use, just paste the function into your javascript file or script tags after jQuery has been loaded.
如果你想在树上查找所有错误,你可以这样做:
最后,
errors
将包含所有错误。不过,您必须将
end_class
添加到您的顶部 div 中。If you want to go up the tree, and get all the errors, you could do something like that:
At the end,
errors
will contain all the errors.You would have to add the
end_class
to your top div though.我做了一些挖掘,发现了一些东西可以获取与选择器匹配的第一个元素,从当前元素开始并向上推进:
阅读有关它的更多信息 此处,您可以使用您的事件来调用此代码。
I did some digging and found something to get the first element that that matches the selector, beginning at the current element and progressing up :
read more about it here and you can use your event to call this code.