我想使用jQuery动态创建HTML表。我有一个充满数据的JS数组。
我尝试过以下操作但它不起作用,没有任何显示。我做错了什么?
Javascript代码
for(var i = 0; i < cycleArr.length; i++) {
var strTable = "<tr>"
for(var j = 0; j < cycleArr[i]; j++) {
var strTable = strTable + "<td>";
var strTable = strTable + cycleArr[i];
var strTable = strTable + "</td>";
}
var strTable = strTable + "</tr>";
}
$('#model_table').append(strTable);
HTML代码
<div id="model_table">
</div>
答案 0 :(得分:1)
假设cycleArr
是一个二维数组(对于其他所有代码都没有多大意义,但如果我错了就纠正我),我发现代码存在以下问题:
j
与cycleArr[i]
进行比较,cycleArr[i].length
可能是一个数组,而不是cycleArr[i]
。cycleArr[i][j]
而不是strTable
。<tr>
变量,因为您要分配strTable
而不是附加它。<tr>
。它只应声明一次。<td>
和<div>
插入<table>
而不是var cycleArr = [['a', 'b', 'c'], ['d', 'e', 'f']];
var strTable = "";
for(var i = 0; i < cycleArr.length; i++) {
strTable += "<tr>"
for(var j = 0; j < cycleArr[i].length; j++) {
strTable += "<td>";
strTable += cycleArr[i][j];
strTable += "</td>";
}
strTable += "</tr>";
}
$('#model_table').append(strTable);
。虽然这可能是有意的,但我认为不是。以下是您的代码的工作版本:
table {
border-collapse: collapse;
}
td {
border: 1px solid grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="model_table">
</table>
Warning: React.createElement: type is invalid -- expected a string (for built-
in components) or a class/function (for composite components) but got:
undefined. You likely forgot to export your component from the file it's
defined in.
Warning: Failed prop type: The prop `history` is marked as required in
`Router`, but its value is `undefined`. in Router
Uncaught TypeError: Cannot read property 'location' of undefined
at new Router (index_bundle.js:8347)
at index_bundle.js:19079
at measureLifeCyclePerf (index_bundle.js:18859)
at ReactCompositeComponentWrapper._constructComponentWithoutOwner (index_bundle.js:19078)
at ReactCompositeComponentWrapper._constructComponent (index_bundle.js:19064)
at ReactCompositeComponentWrapper.mountComponent (index_bundle.js:18972)
at Object.mountComponent (index_bundle.js:4070)
at ReactCompositeComponentWrapper.performInitialMount (index_bundle.js:19155)
at ReactCompositeComponentWrapper.mountComponent (index_bundle.js:19042)
at Object.mountComponent (index_bundle.js:4070)
另外,你写道你有一个“JSON数组”,但看起来你有一个JS(JavaScript)数组。 JSON数组将是一个对数组进行编码的字符串(在解析数据之前,您将无法对其进行迭代,这使得它不再是JSON)。我冒昧地纠正你的帖子以避免混淆。
答案 1 :(得分:0)
我将代码放入一个html文件中。下面是代码。请注意,您需要允许:
strTable - 通过添加+ =继续循环。只需简化var strTable = strTable +&#34;&#34;来自上面的代码。
这里的想法是,你有列和行。首先,您将从左向右循环,然后如果行完成,则需要转到下一行。
<div id="model_table">&npsp;</div> <!-- result here -->
<script type="text/javascript">
var cycleArr = [[1,2,3,4,5], [6,7,8,9,10]];
var strTable = '<table border="1" cellpadding="5">';
for(var i = 0; i < cycleArr.length; i++) {
strTable += "<tr>";
for(var j = 0; j < cycleArr[i].length; j++) {
strTable += '<td>' + cycleArr[i][j] + '</td>';
}
strTable += "</tr>";
}
strTable += '</table>';
document.getElementById('model_table').innerHTML = strTable;
</script>