MIxing变量与jquery中的html

时间:2017-06-09 12:21:56

标签: javascript jquery html

我有一个HTML列表项,我想使用javascript / jquery显示到我的网页。我循环遍历数组,我想使用javascript在HTML列表中显示数组的元素,但我不能让它工作。任何人都知道我的代码有什么问题......

for (m = 0; m < myArray.length; m++){
      $("ul").append("<li>"+myArray[m]+"</li>");
}

2 个答案:

答案 0 :(得分:0)

&#13;
&#13;
var myArray = ['apple', 'mango', 'banana'];

for (var m = 0; m < myArray.length; m++){
      $("ul").append("<li>"+myArray[m]+"</li>");
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>

</ul>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

Do you want a one-liner?

var myArray = ['apple', 'mango', 'banana'];

$('ul').html("<li>"+myArray.join("</li><li>")+"</li>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul>

Using join() you can stringify an Array with a selector of your choice.

EDIT: It is also less resource intensive because it injects the HTML all at once and not in a loop. And we all know that DOM manipulation needs the most resources.