显示阵列使用jQuery的所有项目 [英] Display all items in array using jquery
问题描述
我有我想要显示HTML中的数组..
我不想写多行的数组中张贴的每个项目,但都应该是完全一样的。即
I have an array that I want to have displayed in html.. I don't want to write multiple lines for posting each item in the array but all should be exactly the same. ie
var array = [];
//code that fills the array..
$('.element').html('<span>'+array+'</span>');
我想在这里是创建一个跨度为数组中的每个项目。
what I want here is to create a span for each item in the array.
推荐答案
您可以通过在一个循环中循环访问数组,积累了新的HTML到它自己的数组,然后加入HTML一起,将其插入像这样做进入末的DOM:
You can do it like this by iterating through the array in a loop, accumulating the new HTML into it's own array and then joining the HTML all together and inserting it into the DOM at the end:
var array = [...];
var newHTML = [];
for (var i = 0; i < array.length; i++) {
newHTML.push('<span>' + array[i] + '</span>');
}
$(".element").html(newHTML.join(""));
有人preFER,而不是使用的为
循环jQuery的。每()
方法,它会工作是这样的:
Some people prefer to use jQuery's .each()
method instead of the for
loop which would work like this:
var array = [...];
var newHTML = [];
$.each(array, function(index, value) {
newHTML.push('<span>' + value + '</span>');
});
$(".element").html(newHTML.join(""));
还是因为数组迭代的输出本身就是从每个项目的原始数组中得出一个项目的数组,jQuery的 .MAP
可以这样使用:
var array = [...];
var newHTML = $.map(array, function(value) {
return('<span>' + value + '</span>');
});
$(".element").html(newHTML.join(""));
你应该用的是取决于你的$ P $个人的选择pferred编码风格,灵敏度性能和熟悉 .MAP()
。我的猜测是,为
循环将是最快的,因为它有较少的函数调用,但如果表现的主要标准,那么你就必须标杆实际测量的选项
Which you should use is a personal choice depending upon your preferred coding style, sensitivity to performance and familiarity with .map()
. My guess is that the for
loop would be the fastest since it has fewer function calls, but if performance was the main criteria, then you would have to benchmark the options to actually measure.
仅供参考,在所有这三个选项中,HTML累计到一个数组,然后在最后连接在一起,并一次全部插入到DOM。这是因为DOM操作通常都是这样操作的最慢的部分,因此最好尽量减少单独的DOM操作的数量。结果累加到一个数组,因为项目添加到一个数组,然后在年底加入他们通常比你去添加字符串更快。
FYI, in all three of these options, the HTML is accumulated into an array, then joined together at the end and the inserted into the DOM all at once. This is because DOM operations are usually the slowest part of an operation like this so it's best to minimize the number of separate DOM operations. The results are accumulated into an array because adding items to an array and then joining them at the end is usually faster than adding strings as you go.
而且,如果你能与IE9以上的生活(或安装 .MAP的ES5填充工具()
),你可以使用数组版本 .MAP
是这样的:
And, if you can live with IE9 or above (or install an ES5 polyfill for .map()
), you can use the array version of .map
like this:
var array = [...];
$(".element").html(array.map(function(value) {
return('<span>' + value + '</span>');
}).join(""));
注:此版本还得到在紧凑的利益摆脱 newHTML
中间变量
这篇关于显示阵列使用jQuery的所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!