这是写的页面,我应该得到“我可以打印”,但我只得到标题,页面的其余部分是空白的。错误在哪里?
<!DOCTYPE html>
<html>
<head>
<title>Object exercise 4</title>
</head>
<body>
<h2>Object exercise 4</h2>
<script type = "text/javascript">
function PrintStuff(myDocuments)
{
this.documents = myDocuments;
}
PrintStuff.prototype.print=function()
{
console.log(this.documents);
}
var newObj = new PrintStuff("I can print");
newObj.print();
</script>
</body>
</html>
答案 0 :(得分:3)
console.log()不是用于向页面添加内容的内容。有几种方法可以解决您的问题 - 我已将其中一种方法添加为代码段:
function PrintStuff(myDocuments) {
this.documents = myDocuments;
}
PrintStuff.prototype.print = function() {
var paragraph = document.createElement("p");
paragraph.innerText = this.documents;
document.body.appendChild(paragraph);
console.log(this.documents); // this only prints to the browser console (and throws an exception in IE if the console was not opened before)
}
var newObj = new PrintStuff("I can print");
newObj.print();
<h2>Object exercise 4</h2>
如果您不知道浏览器控制台是什么,请在浏览器中按[F12](这确实很有用)或查看What are browser developer tools?(developer.mozilla.org上的所有内容都很棒)。