有没有办法在某种程度上使用jQuery .append
中的函数?我需要这样的东西:
$("<tbody>").append(function(){
for (i = 0; i < Test1.length; i++){
Test1[i]
}
})
为什么在这种情况下一切正常
$("<tr>").append(
$("<th>").append("#"),
$("<th>").append(THeaders[1]),
$("<th>").append("Tuesday"),
$("<th>").append("Wednesday"),
$("<th>").append("Thurdsday"),
$("<th>").append("Friday"),
$("<th>").append("Saturday")
)
但我收到的元素没有&#34;&lt;第&GT;&#34;在下一个选项中:
$("<tr>").append(
$.each(THeaders, function(i, d){
$("<th>").append($('<th></th>').text(d));
})
)
其中
var THeaders = ["#", "Monday", "Tuesday", "Wednesday", "Thurdsday", "Friday", "Saturday"];
答案 0 :(得分:2)
您可以使用JS .map()
检索每个值,使用模板文字``
将您的值包装在TR
标记中
<强> ES6 强>
var THeaders = ["#", "Monday", "Tuesday", "Wednesday", "Thurdsday", "Friday", "Saturday"];
$('thead tr').append( THeaders.map(val => `<th>${val}</th>`) );
&#13;
th{border: 1px solid #ddd;}
&#13;
<table>
<thead><tr></tr></thead>
</table>
<script src="//code.jquery.com/jquery-3.1.0.js"></script>
&#13;
或JS过时的方式:
var THeaders = ["#", "Monday", "Tuesday", "Wednesday", "Thurdsday", "Friday", "Saturday"];
$('thead tr').append( THeaders.map(function(val) { return '<th>'+ val +'</th>'; }) );
&#13;
th{border: 1px solid #ddd;}
&#13;
<table>
<thead><tr></tr></thead>
</table>
<script src="//code.jquery.com/jquery-3.1.0.js"></script>
&#13;
您尝试使用的 jQuery 方式会错过某种.map
,return
和$ Element构造,如
var THeaders = ["#", "Monday", "Tuesday", "Wednesday", "Thurdsday", "Friday", "Saturday"];
$("<tr/>", {
append: THeaders.map(function(val){
return $('<th/>', {text: val});
}),
appendTo: 'thead'
})
&#13;
th{border: 1px solid #ddd;}
&#13;
<table>
<thead></thead>
</table>
<script src="//code.jquery.com/jquery-3.1.0.js"></script>
&#13;
答案 1 :(得分:0)
看看下面的shoudl给你一个想法去哪儿?
var THeaders = ["#", "Monday", "Tuesday", "Wednesday", "Thurdsday", "Friday", "Saturday"];
var trid = $('#list');
$.each(THeaders, function(i, d){
trid.append('<th>' + d + '</th>');
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table width="100%" cellpadding="1" cellspacing="1">
<tr id="list">
</tr>
</table>
&#13;