运行HTML文件后,页面显示为空白。
var person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
function myFunction() {
document.getElementById("demo").innerHTML = person.firstName + " " + person.lastName;
}
<p id="demo"></p>
可能出现什么问题?
答案 0 :(得分:1)
DOMContentLoaded
完全加载DOM时的更好方法。
var person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
function myFunction() {
document.getElementById("demo").innerHTML = person.firstName + " " + person.lastName;
}
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
myFunction();
});
&#13;
<p id="demo"></p>
&#13;
答案 1 :(得分:0)
为了澄清@tkausl在评论中所说的内容,你已经定义了一个函数,但还没有执行(调用)它。试着这样做:
var person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
function myFunction() {
document.getElementById("demo").innerHTML = person.firstName + " " + person.lastName;
}
myFunction();
<p id="demo"></p>
答案 2 :(得分:-2)
你需要在js代码中的某个地方调用函数..比如:
window.onload="myFunction()";
或者,使其成为一个自动执行的功能:
<script>
(function() {
myFunction()
})();
</script>