jQuery - 直系子级
我有这样的结构:
<ul id="mycustomid">
<li><a>Item A</a>
<ul class="children">
<li><a>Child1 of A</a>
<ul class="children">
<li><a>Grandchild of A</a>
<ul class="children">
<li><a>Grand Grand child of A</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a>Item B</a></li>
<li><a>Item C</a></li>
</ul>
现在,我使用 Jquery 只获取 ul#mycustomid 的直接子级。但我的代码返回了我结构中的所有 li。我应该如何进行?
这是我的代码:
$(document).ready(function() {
var arri = $("#mycustomid>li").text();
alert(arri);
});
我也尝试过 .children()
,它给了我几乎相同的结果。这真的让我很紧张:(
我的警报框输出完全如下所示(包括那些白色间隙):
Item A
Child1 of A
Grandchild of A
Grand Grandchild of A
ItemBItemC
然而,它应该只是(没有空格):
Item A
Item B
Item C
要了解我的问题,您可以在 https://jsfiddle.net/yS6ZJ/
请为我指出正确的方向。
I have a structure like this:
<ul id="mycustomid">
<li><a>Item A</a>
<ul class="children">
<li><a>Child1 of A</a>
<ul class="children">
<li><a>Grandchild of A</a>
<ul class="children">
<li><a>Grand Grand child of A</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a>Item B</a></li>
<li><a>Item C</a></li>
</ul>
Now, I am using Jquery to get only the immediate children of the ul#mycustomid
. But my code returns me with ALL the li's in my structure. How should I proceed?
Here's my code:
$(document).ready(function() {
var arri = $("#mycustomid>li").text();
alert(arri);
});
I have tried .children()
too, it gives me almost the same result. This is really getting on my nerves :(
My alert box outputs exactly as shown below (including those white gaps):
Item A
Child1 of A
Grandchild of A
Grand Grandchild of A
ItemBItemC
Whereas, it should be just (without spaces):
Item A
Item B
Item C
To understand my problem, you can check out the live version at https://jsfiddle.net/yS6ZJ/
Please point me in the right direction.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你的选择器工作得很好 - 这是你用它做的事情有问题。
当您调用
.text()
时,您将获得该元素的所有内容。所有这些,包括子元素。试试这个:
I think that your selector is working just fine - it's what you're doing with it that's got a problem.
When you call
.text()
, you get all the contents of the element. All of it, including the child elements.Try this:
这将解决您的问题:
append('\n')
只是添加换行符,以便它在警报中看起来没问题。要包含所有孙子,您只需删除对
LI
的直接引用:要获取孙子:
要获取每个级别,您可以执行以下操作:
This will solve your issue:
The
append('\n')
is there just to add a line break, so that it looks okay in the alert.To include all grandchildren, you just remove the immediate reference to
LI
:And to just get the grandchildren:
And to get each level, you can go for: