jQuery:选择器问题(最接近)
我有这样的标记:
<div class=gui>
<div class=form>
<div class=textbox></div>
<div class=textbox></div>
<div class=textbox></div>
<div class=selectbox></div>
<div class=selectbox></div>
<div class=button></div>
</div>
</div>
我想做的是迭代 div 并找到它们相应的父母。 例如:
文本框 >表单
选择框>表单
按钮>表格
形式> gui
这是我的 jQuery 选择器:
var dParent = div.closest("div.form, div.gui");
它适用于文本和选择框,但不适用于表单。 奇怪的是,表单将自己报告为父级而不是 GUI。
有什么想法可能是错的吗?
谢谢
i'm having this markup:
<div class=gui>
<div class=form>
<div class=textbox></div>
<div class=textbox></div>
<div class=textbox></div>
<div class=selectbox></div>
<div class=selectbox></div>
<div class=button></div>
</div>
</div>
what i want to do is iterate the divs and find their corresponding parents.
like:
textboxes > form
selectbox > form
button > form
form > gui
here's my jQuery selector:
var dParent = div.closest("div.form, div.gui");
it works nice for the text- and selectboxes, but not for the form.
the strange thing is that the form reports itself as parent instead of the gui.
any ideas what could be wrong?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
.closest()
将选择与选择器匹配的调用元素,因此当您调用$('.form').closest('.form, .gui')
它将返回自身.form
作为最接近的。因此,您只需从.parent()
调用最接近的位置即可:查看示例 →
.closest()
will select the calling element if it matches the selector, so when you call$('.form').closest('.form, .gui')
it will return itself.form
as being the closest. Therefore, you simply want to call closest from the.parent()
:See example →
我最好的猜测是不知道有关该结构的任何其他信息。
Would be my best guess not knowing anything else about the structure.
Closest 的工作原理是从当前元素开始,向上遍历树,直到找到与选择器匹配的元素。当您从表单开始时,表单本身与选择器匹配,因此它被选择。由于您要做的就是找到父级,因此适当的方法是使用 parents 和选择器:
使用类似:
请参阅实际示例:http://jsfiddle.net/tFqLE/
Closest works by starting with the current element and traversing up the tree until it finds an element matching the selector. When you start with the form, the form itself matches the selector so it is chosen. Since all you want to do is find the parent, the appropriate method to use is parents with a selector:
Used like:
See example in action at: http://jsfiddle.net/tFqLE/