有关将数组项加载到JS变量的问题

时间:2016-01-07 22:18:55

标签: javascript jquery

我需要将一个数组的项加载到一个可变的字符串中,以便在页面中动态使用它



var data = ["Sat 17 Jan", "Wed 14 Jan", "Wed 7 Jan"]
var str;

for (i = 0; i < data.length; i++) { 
    str = '<button class="btn btn-success">'+data[i]+'</button>';
}
console.log(str);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

我现在得到的只是控制台中的最后一个按钮:

<button class="btn btn-success">Wed 7 Jan</button>

但我需要

<button class="btn btn-success">Sat 17 Jan</button><button class="btn btn-success">Wed 14 Jan</button><button class="btn btn-success">Wed 7 Jan</button>

3 个答案:

答案 0 :(得分:3)

您需要将每个新按钮附加到字符串,然后使用+=

&#13;
&#13;
var data = ["Sat 17 Jan", "Wed 14 Jan", "Wed 7 Jan"]
var str = "";

for (i = 0; i < data.length; i++) { 
    str += '<button class="btn btn-success">'+data[i]+'</button>';
}
console.log(str);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

&#13;
&#13;
blah / blah / something
&#13;
var data = ["Sat 17 Jan", "Wed 14 Jan", "Wed 7 Jan"];

console.log($.map(data, function(aDate){
  return '<button class="btn btn-success">'+ aDate +'</button>';
}).join(''));
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您在每个循环周期重新分配str。试试这个:

str = str + "your html";
在你的for循环中