我有一个数组,每 12 个项目属于一组数据(我想将该组打印到一个 <tr>
)。例如,如果我的数组有 24 个项目。我想将前 12 项打印在一个 <tr>
中并保持第二名<tr>
等等。谁能告诉我如何做到这一点。谢谢
示例数组:
var myArray = ["1","first","Mixed","http://www.somesite.com/12.jpg","chicago","http://www.somesite.com/countries/1.jpg","false","http://www.somesite.com/logos/87.jpg","http://www.somesite.com/logos/87.jpg","winter","summer","http://somesite.com/list/thumb.jpg"];
这是我构建数组的方式:
$.each($xml.find('dict>string'), function (i) {
var keyName = $(this).text();
myArray.push(keyName);
}
示例<tr>
通过 javascript 打印:
<tr id="1">
<td>1</td>
<td><img src="http://somesite.com/list/thumb.jpg" height="42" width="42"></td>
<td>
<a href="javascript:doit('id=1&name=first&type=Mixed&logo1=http://www.somesite.com/12.jpg&city=chicago&logo2=http://www.somesite.com/countries/1.jpg&order=false&logo3=http://www.somesite.com/logos/87.jpg&logo4=http://www.somesite.com/logos/87.jpg&season=winter&season2=summer&thumb=http://somesite.com/list/thumb.jpg','chicago')" onclick="selectLink(this);">chicago</a><br>
<br></td></tr>
最佳答案
您真正需要做的是重构数据以使用对象数组,其中每个对象包含单个表行的所有键值对。
现在构建 html 很简单。
当我们这样做时,让我们摆脱链接上的内联 JavaScript 并改用事件处理程序:
var myArray = [{
id: 1,
name: 'first',
type: 'Mixed',
season: 'winter',
season2: 'summer',
logo1: 'http://www.somesite.com/12.jpg&city=chicago',
logo2: 'http://www.somesite.com/countries/1.jpg',
logo3: 'http://www.somesite.com/logos/87.jpg',
logo4: 'http://www.somesite.com/logos/87.jpg',
order: false,
thumb: 'http://somesite.com/list/thumb.jpg',
city: 'chicago'
}, {
id: 1,
name: 'last',
type: 'someType',
season: 'fall',
season2: 'spring',
logo1: 'http://www.somesite.com/12.jpg&city=chicago',
logo2: 'http://www.somesite.com/countries/1.jpg',
logo3: 'http://www.somesite.com/logos/87.jpg',
logo4: 'http://www.somesite.com/logos/87.jpg',
order: true,
thumb: 'http://somesite.com/list/thumb.jpg',
city: 'new york'
}, ];
$.each(myArray,function(i, object){
var $row = $('<tr>');
$row.append( $('<td></td>', {text:object.id}));
$row.append( $('<td></td>').append( $('<img>', {src:object.thumb, height:42, width:42}))) ;
$row.append( $('<td></td>').append( $('<a></a>', {href:'#', text:object.city, class:'doIt'}).data(object)));
$('#myTable').append($row);
});
$('#myTable').on('click','.doIt',function(e){
// use this handler to access the data on the link
// put your logic from "doIt()" in here instead
e.preventDefault();
var $this=$(this);
console.log($this.data('name'));
console.log($this.data('type'));
console.log($this.data('season'));
// etc....
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
</table>
关于javascript - 如何将数组的每 12 项添加到一个 <tr> 集合中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39927207/