[英]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.