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

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

最佳答案

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

关于javascript - 将不同的列表项添加到无序列表数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38254486/

相关文章:

javascript - jquery SlideDown 而不是 SlideAndPush

javascript - 使用复选框为字段设置 val()

javascript - 使用 moment 和 moment 时区正确实现 diff

javascript - 渲染中的箭头函数与。携带数据的属性

jquery 对话框按钮的 tabindex

javascript - 如何使隐藏的元素更快地弹出(jquery/css)

javascript - jQuery DataTables 使用下拉选择就地编辑单元格

javascript - 图像/div 在谷歌浏览器中悬停时闪烁

javascript - 更改 Javascript 对象中所有 undefined variable 的值

javascript - 确保两个单独的对象具有唯一的总键集