2016-07-07 6 views
1

同じクラスを持つ3つの順序付けられていないリストがあります。私はそれらをループして、それぞれに特定の説明に一致する項目を追加しようとしていますが、インデックスでリストを参照しようとすると、追加機能が見つからないと表示されます。アクセスするとき並べ替えられていないリストの配列に異なるリスト項目を追加する

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

答えて

4

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

}); 

すべてのリストに項目を追加する(私は明らかにこれを行うにはしたくないが)何らかの理由で正常に動作するようです:コードは次のようになりますインデックスによるjQueryオブジェクトは、jQueryオブジェクトではなくDOMElementを返します。したがって、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); 
    } 
}); 
+0

おかげで、すぐにそれを修正! – Organiccat

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>

代わりに、あなたはjQueryオブジェクトに包まれたインデックスにある要素を取得するためにeqメソッドを使用することができます。

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>

関連する問題