简体   繁体   English

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

[英]JavaScript prints nothing to the page

After running the HTML file the page appears blank.运行 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>

What might be wrong?可能有什么问题?

  • A better approach, when the DOM is fully loaded using the event DOMContentLoaded .更好的方法,当使用事件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(); });
 <p id="demo"></p>

To clarify what @tkausl said in the comment, you have defined a function, but have yet to execute (called) it.为了澄清@tkausl 在评论中所说的内容,您已经定义了一个函数,但尚未执行(调用)它。 Try doing this:尝试这样做:

 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>

You need to call the function somewhere in the js code.. Something like:您需要在 js 代码中的某处调用该函数.. 类似于:

window.onload="myFunction()";

Or, make it a self executing function:或者,使它成为一个自执行函数:

<script>
(function() {
    myFunction()
})();
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM