<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="myFirstStyleSheet.css">
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$.getJSON('/Users/skhare/tableList.json', function(tableList) {
var output="<table id=tableStyle>";
output+="<tr>" + "<th>" + "Table Names" + "</th>" + "</tr>";
for (var i in tableList.t)
{
output+="<tr>" + "<td>" + "<a href=/Users/skhare/tableDescription.html>" + tableList.t[i].name + "</a>" + "</td>" + "</tr>";
}
output+="</table>";
document.getElementById("placeholder").innerHTML=output;
});
</script>
</head>
<body>
<div id="placeholder"></div>
</body>
</html>
上述代码不显示任何内容,也不显示任何错误。 json文件如下:
{"t":
[
{"name":"DIM_BROWSER"},
{"name":"DIM_CAMPAIGN"},
{"name":"DIM_COLOR_DEPTH"},
{"name":"DIM_CONNECTION_TYPE"},
{"name":"DIM_COUNTRY"},
{"name":"DIM_GEOGRAPHY"},
{"name":"DIM_JAVASCRIPT_VERSION"},
{"name":"DIM_LANGUAGE"},
{"name":"DIM_OPERATING_SYSTEM"},
{"name":"DIM_PAGENAME"}
]
}
答案 0 :(得分:2)
将脚本代码放在$(document).ready()
中在文档准备好之前,页面无法安全操作。&#34; jQuery为您检测这种准备状态。 $( document ).ready()
中包含的代码只有在页面文档对象模型(DOM)准备好执行JavaScript代码后才会运行。
$(document).ready(function(){
$.getJSON('/Users/skhare/tableList.json', function (tableList) {
var output = "<table id=tableStyle>";
output += "<tr>" + "<th>" + "Table Names" + "</th>" + "</tr>";
for (var i in tableList.t) {
output += "<tr>" + "<td>" + "<a href=/Users/skhare/tableDescription.html>" + tableList.t[i].name + "</a>" + "</td>" + "</tr>";
}
output += "</table>";
document.getElementById("placeholder").innerHTML = output;
});
})
答案 1 :(得分:0)
正如已经指出的那样,这对你不起作用的原因是你试图在DOM完成渲染之前操纵元素(即<div id="placeholder">
)并且它们出现在页面上。
但是,我的建议是将所有JavaScript移至结束</body>
标记之前,而不是使用$(document).ready()
。这有助于保持代码的有序性(因为所有的JS都在一个地方)并且具有额外的优势,到目前为止,DOM将根据定义进行呈现。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="myFirstStyleSheet.css">
</head>
<body>
<div id="placeholder"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$.getJSON('/Users/skhare/tableList.json', function(tableList) {
var output="<table id=tableStyle>";
output+="<tr>" + "<th>" + "Table Names" + "</th>" + "</tr>";
for (var i in tableList.t)
{
output+="<tr>" + "<td>" + "<a href=/Users/skhare/tableDescription.html>" + tableList.t[i].name + "</a>" + "</td>" + "</tr>";
}
output+="</table>";
document.getElementById("placeholder").innerHTML=output;
});
</script>
</body>
</html>