将数组中的第一项包装在标签中,将以下项目包装在其他标签中

时间:2016-04-02 17:50:59

标签: javascript jquery arrays lodash

好的,我们假设我有一系列项目,如[1,a,b,c]。

我想要达到的目标是:

<span>1</span>
<p>a</p>
<p>b</p>
<p>c</p>

如果我可以为元素分配相应的类名,例如class =“1”,class =“a”......等等,那也很酷。

2 个答案:

答案 0 :(得分:1)

您可以使用$.map()

var arr = [1,"a","b","c"]; var els = ["<span/>", "<p/>"];

var elems = $.map(arr, function(value, index) {
  return $(index === 0 ? els[0] : els[1], {html:value, "class":value})[0]
});

console.log(elems);

$("body").html(elems)

&#13;
&#13;
var arr = [1,"a","b","c"]; var els = ["<span/>", "<p/>"];

var elems = $.map(arr, function(value, index) {
  return $(index === 0 ? els[0] : els[1], {html:value, "class":value})[0]
});

console.log(elems);

$("body").html(elems)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<body></body>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用数组"

map

var array = ["1","a","b","c"];