将数组中的第一项包装在标签中,将以下项目包装在其他一些标签中
Wrap the first item in array in tag and the following ones in some other tags
好的,让我们假设我有一个像这样的项目数组 [1,a,b,c]。
我想要实现的是这样的:
<span>1</span>
<p>a</p>
<p>b</p>
<p>c</p>
如果我可以为元素分配一个相应的 class 名称,如 class="1", class="a"...很快。
您可以使用$.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)
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)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<body></body>
通过使用数组 map
var array = ["1","a","b","c"];
array.map(function(i,v){
$("#someDiv").append(i == 0? "<span class='"+v+"'>"+v +"</span>" : "<p class='"+v+"'>"+v +"</p>";
});`
好的,让我们假设我有一个像这样的项目数组 [1,a,b,c]。
我想要实现的是这样的:
<span>1</span>
<p>a</p>
<p>b</p>
<p>c</p>
如果我可以为元素分配一个相应的 class 名称,如 class="1", class="a"...很快。
您可以使用$.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)
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)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<body></body>
通过使用数组 map
var array = ["1","a","b","c"];
array.map(function(i,v){
$("#someDiv").append(i == 0? "<span class='"+v+"'>"+v +"</span>" : "<p class='"+v+"'>"+v +"</p>";
});`