我使用 jQuery 的each/getJSON 循环遍历我的data.json
文件,抓取数据并格式化数据,然后将其输出到#output
内的页面上> 分区。
它按预期工作,除了 [object HTMLElement]
奇怪地添加到渲染的 HTML 之前。
$.getJSON( 'json/data.json', function ( data ) {
var output;
$.each( data, function ( index, entry ) {
output += '<div class="entry" id="' + entry.date + '">';
$.each( entry.exercises, function ( index, exercise ) {
var i = 1;
output += '<table class="exercise"><tr><th>' + exercise.name
+ '</th><th>Weight</th><th>Reps</th></tr>';
$.each( exercise.stats, function ( index, stat ) {
output += '<tr><td>SET ' + i++ + '</td><td><input type="number" placeholder="'
+ stat.weight + '"></td><td><input type="number" placeholder="'
+ stat.reps + '"></td></tr>';
});
output += '</table>';
});
output += '</div>';
}); // each
$( '#output' ).html( output );
}); // getJSON
data.json
[
{
"date" : 12252014,
"exercises" : [
{
"name" : "Squats",
"stats" : [
{ "weight" : 135, "reps" : 5 },
{ "weight" : 225, "reps" : 10 },
{ "weight" : 315, "reps" : 15 }
]
},
{
"name" : "Bench",
"stats" : [
{ "weight" : 435, "reps" : 20 },
{ "weight" : 525, "reps" : 15 },
{ "weight" : 615, "reps" : 30 }
]
},
{
"name" : "Rows",
"stats" : [
{ "weight" : 735, "reps" : 35 },
{ "weight" : 825, "reps" : 40 },
{ "weight" : 915, "reps" : 45 }
]
}
]
}
]
HTML 错误:
<div id="output">
"[object HTMLElement]"
<div class="entry" id="12252014" style="display: none;">
<table class="exercise">
<tbody>
<tr>
<th>Squats</th>
<th>Weight</th>
<th>Reps</th>
</tr>
<tr>
<td>SET 1</td>
<td><input type="number" placeholder="135"></td>
<td><input type="number" placeholder="5"></td>
</tr>
<tr>
<td>SET 2</td>
<td><input type="number" placeholder="225"></td>
<td><input type="number" placeholder="10"></td>
</tr>
<tr>
<td>SET 3</td>
<td><input type="number" placeholder="315"></td>
<td><input type="number" placeholder="15"></td>
</tr>
</tbody>
</table>
[...]
</div>
</div>
为什么将 [object HTMLElement]
添加到输出中?
最佳答案
对我来说,这看起来像是变量 output
allready 之前已使用过并填充了 html 元素。
在你的例子中,它是你的包装器div,其id为output
,它作为全局变量公开。
您应该能够通过为输出提供初始值来克服这个问题:
var output = '';
因为使用 var
不会清除现有变量:
var output = 'Lorem ipsum';
var output;
alert(output)
关于javascript - 对象未定义/HTMLElement 分别使用 jQuery 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27755545/