<html><head>
<link type="text/css" rel="stylesheet" href="file:///C:/Users/Documents/style.css" />
<script type="text/javascript" src="file:///C:/Users/Documents/jquery-1.7.1.js"></script>
<script type="text/javascript" src="file:///C:/Users/Documents/jquery.tablesorter.js"></script>
<script type="text/javascript">
$(document).ready(function() {
load();
});
var map1 = { "iDate":"test_value1", "iName":"test_value2" , "iFile":"test_value3" };
var map2 = { "iDate":"nexttest_value1", "iName":"nexttest_value2", "iFile":"nexttest_value3" };
var list = new Array( map1, map2 );
list[0] = map1;
list[1] = map2;
function load() {
var beginTD = $( "<td><div class='scroll-pane horizontal-only' style='vertical-align: top'>" );
var endTD = $( "</div></td>" );
jQuery.each( list, function( index, map ) {
$( "#hpTable > tbody:last" ).append( $( "<tr>" ) );
jQuery.each( map, function( key, value ) {
var pTag = $( "<p id='" + key + "'>" + value + "</p>" );
$( "#hpTable td:last" ).append( beginTD, pTag, endTD );
});
$( "#hpTable" ).append( $( "</tr>" ) );
});
};
</script>
</head>
<body>
<br>
<table id="hpTable" cellpadding="5" width="100%" style="table-layout:fixed" class="tablesorter">
<thead><tr>
<th width="9%">Date</th>
<th width="9%">Name</th>
<th>File</th>
</tr>
</thead>
<tbody></tbody>
</table>
</body
</html>
大家好!感谢您查看我的第二篇文章。我是一个jquery新手,并寻找弄清楚为什么我不能动态构建行和单元格?任何帮助表示赞赏!
答案 0 :(得分:1)
正如FrédéricHamidi所说,你不打开和关闭jQuery中的标签,你只需在另一个标签内添加一个标签,并将其用作简单变量来做一些事情。
然后你的“每个”解析应该如下所示:
jQuery.each( list, function( index, map ) {
// you create a tr tag and attached it to your table body
var trTag = $( "<tr></tr>" ).appendTo($( "#hpTable > tbody"));
jQuery.each( map, function( key, value ) {
var tdTag = $('<td/>').appendTo(trTag);
var divTag = $("<div class='scroll-pane horizontal-only' style='vertical-align: top'/>").appendTo(tdTag);
var pTag = $( "<p id='" + key + "'>" + value + "</p>" ).appendTo(divTag);
});
});
};
答案 1 :(得分:1)
如果你要为一个表构建HTML,你可以通过在一个简单的Javascript字符串中构建它来获得更好的性能,然后在最后添加一次DOM。像这样:
function load() {
var html = [];
var beginTD = "<td><div class='scroll-pane horizontal-only' style='vertical-align: top'>";
var endTD = "</div></td>";
jQuery.each( list, function( index, map ) {
html.push('<tr>');
jQuery.each( map, function( key, value ) {
html.push(beginTD, "<p id='" + key + "'>" + value + "</p>", endTD);
});
html.push('</tr>');
});
$( "#hpTable tbody" ).append(html.join('\n'));
};
我编辑了原始解决方案以构建数组并使用换行符加入。这比“+ =”连接运算符更有效,特别是在IE中。