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

时间:2016-07-07 20:14:36

标签: javascript jquery

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

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);

2 个答案:

答案 0 :(得分:4)

当通过索引访问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);
    }
});

答案 1 :(得分:0)

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>

相关问题