简体   繁体   English

在jQuery选择器中使用jQuery对象

[英]Using jQuery objects in jQuery selectors

I'm fairly new to jQuery, and think I might be making something harder than it needs to be. 我对jQuery很新,并且认为我可能会做出比它需要的更难的东西。 I've got a jQuery variable that is just an unordered list. 我有一个jQuery变量,它只是一个无序列表。 It was declared this way: 它是这样声明的:

var $list = $('#activityList'); // activityList is ID of <ul>

I'm trying to select all <li> elements within that list using the variable I've created: 我正在尝试使用我创建的变量选择该列表中的所有<li>元素:

$items = $('#' + $list.attr('id') + ' > li');

Does anyone know if there's a different syntax to achieve the same thing without having to break the variable down to it's id attribute? 有没有人知道是否有不同的语法来实现相同的事情而不必将变量分解为它的id属性?

Thanks. 谢谢。

Clarification: I used simplified code for the purposes of asking the question, but I do want to make use of the jQuery variable "$list" within the selector, rather than hardcoding the ID. 澄清:我使用简化代码来提问,但我确实想在选择器中使用jQuery变量“$ list”,而不是硬编码ID。

$items = $('li', $list); 

那应该做你想要的。

$("#activitylist > li") would work, as > traverses content. $(“#activitylist> li”)可以工作,因为>遍历内容。 You can also use, with $list as a JQuery object: 您还可以使用$ list作为JQuery对象:

$list.find("li") or $list.children("li") to find the list items as well. $ list.find(“li”)或$ list.children(“li”)也可以查找列表项。 children would be more efficient if you are only looking for immediate children. 如果你只是寻找直接的孩子,孩子会更有效率。

尝试这个:

var items = $('#activityList > li');

也许我误解了,但是错在哪里......

var $items = $('#activityList > li'); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM