我有两个数组state
和memlist
,您可以看到我正在将memlist
的元素加载到#list
ul。这是通过使用.each()
函数来实现的,但我仍然需要将state
的元素作为类定义加载到<li>
中,如下所示:
memlist.append($( '<li class="'+ state[i] +'">' + value + '</li>' ));
请告诉我如何在jQuery中执行此操作?
var memlist = $( "#list" );
var states = ['one','two','three'];
var members = [ "John", "Steve", "Ben", "Damon", "Ian" ];
$.each(members,function( index, value ){
memlist.append($( "<li>" + value + "</li>" ));
});
由于
答案 0 :(得分:1)
当它达到状态长度时,它重新开始
var memlist = $( "#list" );
var states = ['one','two','three'];
var members = [ "John", "Steve", "Ben", "Damon", "Ian", "test"];
var counter = 0;
$.each(members,function( index, value ){
//console.log(counter);
memlist.append($( "<li class="+states[counter]+">" + value + "</li>" ));
counter++;
if(counter == states.length){
counter=0;
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<ul id="list"></ul>
&#13;
答案 1 :(得分:0)
首先确保states
和members
中的元素数量相同。
如果是这样,那么您可以执行以下操作。
var states = ['one','two','three'];
var members = [ "John", "Steve", "Ben", "Damon", "Ian" ];
$.each(members,function( index, value ){
// Now index will be helpful to traverse through states array so
memlist.append("<li class = '"+states[index]+"'>" + value + "</li>")
});
答案 2 :(得分:0)
我试过这个没问题。
$.each(members,function( index, value ){
var clas =(index < states.length) ? states[index] : null;
memlist.append('<li class="'+clas+'">' + value + '</li>' );
});
答案 3 :(得分:0)
var states = [one,two,three];
var members = [ "John", "Steve", "Ben", "Damon", "Ian" ];
var element_html="";
for(var i=0 ; i < members.length ; i++) {
element_html += <li class=;
element_html += state[k];
element_html += >;
element_html += value;
element_html +=</li>;
}
$("#list").html(element_html);
k is what ever you want to choose from state list