繁体   English   中英

将不同的列表项添加到无序列表的数组

[英]Adding different list items to array of unordered lists

我有三个具有相同类的无序列表。 我遍历它们,并尝试向它们每个添加与某些描述匹配的项目,但是当我尝试通过其索引引用列表时,它说找不到附加函数。 代码看起来像这样:

demoTypes.upcomingDemos.map(function(item) {
    var itemElement = "<li>My Item</li>";
    if (demoTypes.type == "Basic") {
        $(".unorderedListSection")[0].append(itemElement);
    } else if (demoTypes.type == "Intermediate") {
        $(".unorderedListSection")[1].append(itemElement);
    } else if (demoTypes.type == "Advanced") {
        $(".unorderedListSection")[2].append(itemElement);
    }

});

由于某些原因,将项目添加到所有列表中似乎可以正常工作(尽管我显然不想这样做):

$(".unorderedListSection").append(itemElement);

当通过索引访问jQuery对象时,它返回一个DOMElement而不是jQuery对象,因此您会收到有关缺少append()方法的错误。

要解决此问题,请使用eq()方法:

demoTypes.upcomingDemos.map(function(item) {
    var itemElement = "<li>My Item</li>";
    if (demoTypes.type == "Basic") {
        $(".unorderedListSection").eq(0).append(itemElement);
    } else if (demoTypes.type == "Intermediate") {
        $(".unorderedListSection").eq(1).append(itemElement);
    } else if (demoTypes.type == "Advanced") {
        $(".unorderedListSection").eq(2).append(itemElement);
    }
});

jQuery函数返回一个对象,该对象是围绕元素数组的包装。 当您访问给定索引( $(selector)[index] )的项目时,您将不再具有jQuery对象,而是一个原始元素。

 console.log($('p').html()); console.log($('p')[0].toString()); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>A</p> <p>B</p> <p>C</p> 

相反,您可以使用eq方法在包装在jQuery对象中的索引处获取元素。

 console.log($('p').eq(0).html()); console.log($('p').eq(1).html()); console.log($('p').eq(2).html()); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>A</p> <p>B</p> <p>C</p> 

暂无
暂无

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

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