jQuery 选择器、语法还是错误?
这很奇怪,我在 jquery 中有这样的标记
<div id='div1'>
<ul id='ul1'>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<div id='div2'>
<ul id='ul2'>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
</div>
</div>
,我有一个这样的选择器:
var el = $('#div2');
var liList = el.children('ul:first > li');
应该返回第二组 li,但它返回第一组。 但如果我这样做:
var el = $('#div2');
var liList = el.children('ul:first').children('li');
它会返回第一组。有什么想法吗?
这让我重新考虑,因为第一组 li 甚至不是 div2
的子级,
我显然可以将代码更改为后者,但这是一个错误还是我只是没有编写我的选择器正确吗?
更新:
我正在运行 jquery 1.4.1 并使用下面建议的 jsfiddle 显示 1.4.2(最接近我的配置的选项)和 1.4.4 的不同结果。所以看起来部分是我写了一个错误的选择器,正如 Rocket 所指出的,jquery 团队修复了 1.4.1 中的一个错误。 :)
一定喜欢 StackOverflow :)
This is weird I have markup like this
<div id='div1'>
<ul id='ul1'>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<div id='div2'>
<ul id='ul2'>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
</div>
</div>
in jquery I have a selector like this:
var el = $('#div2');
var liList = el.children('ul:first > li');
That should return the second set of li's but it returns the first set.
But if I do this:
var el = $('#div2');
var liList = el.children('ul:first').children('li');
It returns the first set. Any ideas what's going on?
This made me take a double take because the 1st set of li's aren't even children of div2
I can obviously change my code to the latter, but is it a bug or am I just not writing my selector correctly?
UPDATE:
I was running jquery 1.4.1 and using jsfiddle like was suggested below showed different results with 1.4.2(the closest option to my config) and 1.4.4. So it seems like it was partly I wrote a wrong selector as indicated by Rocket and the jquery team fixed a bug that was in 1.4.1. :)
Gotta love StackOverflow :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
.children()
返回“直接子级”。ul2
及其li
是div2
的子级,但只有ul2
是“直接子级”。要获取所有li
,您需要使用第二个。li
是其各自ul
的“直接子代”。我希望这是有道理的。
jsFiddle
.children()
returns 'immediate children'.ul2
and itsli
s are children ofdiv2
, but ONLYul2
is an 'immediate child'. To get all theli
s, you need to use the second one.The
li
s are 'immediate children' of their respectiveul
.I hope this makes sence.
jsFiddle
这与 DIV2 位于 DIV1 内有关吗?
Is it something to do with DIV2 being inside DIV1?