简体   繁体   English

孩子们()只选择第一个孩子

[英]children() only selecting first child

Given the following unordered list: 鉴于以下无序列表:

<ul class="nb">
    <li class="home"><a href="index.html" class="current"><span class="displace">Home</span></a></li>
    <li class="products"><a href="products.html" title="Products"><span class="displace">Products</span></a></li>
    <li class="services"><a href="services.html" title="Services"><span class="displace">Services</span></a></li>
    <li class="support"><a href="support.html" title="Support"><span class="displace">Support</span></a></li>
    <li class="company"><a href="company.html" title="Company"><span class="displace">Company</span></a></li>
    <li class="contact"><a href="contact.html" title="Contact"><span class="displace">Contact</span></a></li>
</ul>

Can you tell me why the following only selects the first list item: 你能告诉我为什么以下只选择第一个列表项:

var status = 'closed';
$('ul.nb li a').click(function(e){
    e.preventDefault();
        if ($status == 'closed'){
            var li = $(this).closest('li');
            var items = li.parent().children();
            console.log(items.html());
        }
});

Expected results are a selection of all list items, console shows <a href="index.html" class="current"><span class="displace">Home</span></a> 预期结果是所有列表项的选择,控制台显示<a href="index.html" class="current"><span class="displace">Home</span></a>

TIA TIA

html as getter only returns html content of the first selected element, items in your code is a jQuery wrapped array of all the selected li elements. html as getter只返回第一个选定元素的html内容,代码中的items是所有选定li元素的jQuery包装数组。 http://jsfiddle.net/MKUGv/ http://jsfiddle.net/MKUGv/

Because .html() doesn't go through each element of the jQuery object and concat all their html values. 因为.html()不会遍历jQuery对象的每个元素并连接所有的html值。 It only returns the first one's html value. 它只返回第一个的html值。

Since li is all the children, you will have to loop through them on your own. 由于li是所有孩子,你必须自己循环。 Something like: 就像是:

var html = '';
items.each(function(i, elm) {
    html += $(elm).html();
});

I think this is what you are looking for... (logging the html for each li) 我认为这就是你要找的东西......(记录每个li的html)

http://jsfiddle.net/Z2Rhx/ http://jsfiddle.net/Z2Rhx/

$(items).each(function() { console.log($(this).html()) });

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

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