出于某种原因,这对我没有任何意义。我正在尝试创建一个从1到num
的数字列表,其中任何数字都与接收特殊类名的数组中的数字相匹配。代码如下:
<ul id="bb"></ul>
var arr = ['2', '6', '10'];
var num = 25;
var i = 0;
var li = '';
while (i <= num) {
for (x in arr) {
if (i === parseInt(arr[x], 10)) {
li += '<li class="jj">'+ i +'</li>';
} else {
$('#bb').append('<li>'+ i +'</li>');
}
}
//li += '<li>'+ i +'</li>';
$('#bb').html(li);
i++;
}
我该怎么做?
答案 0 :(得分:2)
因为你要覆盖html
var arr = ['2', '6', '10'];
var num = 25;
var i = 0;
var li = '';
while (i <= num) {
//use Array.indexOf() to check whether array contains the value, the `+ ''` is used to convert `i` value to a string since the array contains string values
if (arr.indexOf(i + '') > -1) {
li += '<li class="jj">' + i + '</li>';
} else {
li += '<li>' + i + '</li>';
}
i++;
}
//set the content of the ul at the end of the loop since `li` will have all the required html
$('#bb').html(li);
&#13;
.jj {
color: red
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="bb"></ul>
&#13;