如何将 jQuery 选择器与对象一起使用?
我在一个对象中有一个无序列表:
var myUL = $('ul#theID'); //I send this var to another function in the code
我只想要这个对象的直接子对象(我在每个“li”中还有另一个“ul”,其中也有“li”),但是这个选择器不起作用:
$(myUL + '>li').each( etc, etc...
它给了我Firebug 中此选择器上出现错误“未捕获的异常:语法错误,无法识别的表达式:[object Object]”。
如果我使用 $('li', myUL)
它会给我 ul 中的所有 'li',而不仅仅是直接子级,这不是我想要的。我只想要直系孩子。
正确的语法是什么?
I have an unordered list in an object:
var myUL = $('ul#theID'); //I send this var to another function in the code
I want the direct children only of this object (I have another 'ul' within each 'li' that also has 'li's in it), but this selector does not work:
$(myUL + '>li').each( etc, etc...
It gives me the error "uncaught exception: Syntax error, unrecognized expression: [object Object]" on this selector in Firebug.
If I use $('li', myUL)
it gives me ALL of the 'li's withing the ul, not just the direct children, which is not what I want. I only want the direct children.
What is the correct syntax?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试
(正确地,
只能有
子级。)
Try
(Properly, a
<ul>
can only have<li>
children anyway.)这应该足够了吧?
That should be sufficient?
您无需在以 ID 结尾的选择器开头使用标签名称。仅 ID 是最快的选择器。使用直接子方法将比选择器更快。另外,不向 .children() 方法添加选择器将允许 jQuery 跳过不需要的过滤步骤,因为无论如何您都应该拥有所有“li”子级:
干杯,
阿维里克
You need not use the tag name at the start of a selector that ends with an ID. ID alone is the fastest selector. Using a direct children method will be faster than a selector. Also not adding in a selector to the .children() method will allow jQuery to skip the filtering step that shouldn't be required as you should have all 'li' children regardless:
Cheers,
awirick