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