JavaScript不会向页面打印任何内容

时间:2018-02-17 19:51:46

标签: javascript html

运行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>

可能出现什么问题?

3 个答案:

答案 0 :(得分:1)

  • 使用事件DOMContentLoaded完全加载DOM时的更好方法。

&#13;
&#13;
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;
&#13;
&#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>