如何使用jquery循环对象数组的值?

时间:2014-01-31 08:14:48

标签: jquery

我有两个像这样的数组

var v1 = ["1","2","3","4","5"],
    v2 = ["val1","val2","val3","val4","val5"]

我想匹配值并创建html字符串为;

<div data-id="1">val1</div>
<div data-id="2">val3</div>
<div data-id="3">val3</div>
<div data-id="4">val4</div>
<div data-id="5">val5</div>

如何使用jquery执行此操作?

2 个答案:

答案 0 :(得分:1)

如果要创建html字符串,请使用$.map()

var a1 = ["1", "2", "3", "4", "5"]
var a2 = ["val1", "val2", "val3", "val4", "val5"]

var html = $.map(a1, function (val, i) {
    return '<div data-id="' + val + '">' + a2[i] + '</div>'
}).join('');

console.log(html)

演示:Fiddle

答案 1 :(得分:0)

试试这个:

var ids = ["1","2","3","4","5"]
var values = ["val1","val2","val3","val4","val5"]

$.each(ids, function( index, value ) {
  $('body').append($('<div data-id="' + value + '">' + values[index] + '</div>'));
});