Javascript jQuery 查找并列出特定 DIV 内 UL 内的所有 LI 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7101945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Find and List all LI elements within a UL within a specific DIV
提问by chris
I have 3 Columns of ULs each a Dynamic UL container that can have anywhere from 0-9 LI containers (eventually more). All my LI elements have an attribute "rel" which I am trying to ultimately find that attribute and use it for something else on all LI elements within that parent DIV. I do eventually want to find more based on each but for not the very least the rel.. Any Ideas how I can achieve that with jQuery? Example:
我有 3 列 UL,每列都是一个动态 UL 容器,可以有 0-9 个 LI 容器(最终更多)。我所有的 LI 元素都有一个属性“rel”,我试图最终找到该属性并将其用于该父 DIV 中所有 LI 元素的其他内容。我最终确实想找到更多基于每个但并非最不重要的 rel .. 任何想法我如何用 jQuery 实现这一目标?例子:
<ul id="column1">
<li rel="1">Info</li>
<li rel="2">Info</li>
<li rel="3">Info</li>
</ul>
<ul id="column2">
<li rel="4">Info</li>
<li rel="5">Info</li>
<li rel="6">Info</li>
</ul>
<ul id="column3">
<li rel="7">Info</li>
<li rel="8">Info</li>
<li rel="9">Info</li>
</ul>
these elements are all sortable as well. So when I get a list of them I want to also keep them in the order they were found from top to bottom of each column.
这些元素也都是可排序的。因此,当我获得它们的列表时,我还想按照从每列的顶部到底部找到它们的顺序保留它们。
I have tried find(), parent(), and similar, maybe I am approaching it wrong. But its still worth mentioning to help come up with an idea
我尝试过 find()、parent() 和类似的方法,也许我的方法是错误的。但它仍然值得一提,以帮助提出一个想法
回答by pixelfreak
Are you thinking about something like this?
你在想这样的事情吗?
$('ul li').each(function(i)
{
$(this).attr('rel'); // This is your rel value
});
回答by Fresheyeball
var column1RelArray = [];
$('#column1 li').each(function(){
column1RelArray.push($(this).attr('rel'));
});
or fp style
或 fp 风格
var column1RelArray = $('#column1 li').map(function(){
return $(this).attr('rel');
});
回答by Joseph Silber
$('li[rel=7]').siblings().andSelf();
// or:
$('li[rel=7]').parent().children();
Now that you added that comment explaining that you want to "form an array of rels per column", you should do this:
既然您添加了解释您想要“为每列形成一个 rels 数组”的注释,您应该执行以下操作:
var rels = [];
$('ul').each(function() {
var localRels = [];
$(this).find('li').each(function(){
localRels.push( $(this).attr('rel') );
});
rels.push(localRels);
});
回答by Ahmad Aghazadeh
html
html
<ul class="answerList" id="oneAnswer">
<li class="answer" value="false">info1</li>
<li class="answer" value="false">info2</li>
<li class="answer" value="false">info3</li>
</ul>
Get index,text,value js
获取索引、文本、值 js
$('#oneAnswer li').each(function (i) {
var index = $(this).index();
var text = $(this).text();
var value = $(this).attr('value');
alert('Index is: ' + index + ' and text is ' + text + ' and Value ' + value);
});