2017-10-16 100 views
0

我正在做一個令人難以置信的基本JavaScript練習,用於練習Objects的學校。我認爲普通的document.write可以工作,但它不會,我查了許多地方,但很多地方只是用於控制檯。 錯誤是如何將Javascript對象寫入文檔。在'文檔'上執行'寫入'失敗

無法在'文檔'上執行'寫':除非明確打開,否則無法從異步加載的外部腳本寫入文檔。

如果有人可以幫助這將是巨大的,對不起,如果它真的很容易

這裏是我的代碼

var oPerson = { 
 
    firstName: 'John', 
 
    lastName: 'Travis', 
 
    gender: 'Male', 
 
    age: 22, 
 
    district: 'Northshore', 
 
    hairColor: 'Brown', 
 
    hairLength: 'Short', 
 
    height: '6\'11"', 
 
    weight: '74kg', 
 
    martialStatus: 'Engaged' 
 
} 
 

 
document.write(oPerson); 
 
document.write(oPerson.district); 
 

 
oPerson.resident = "yes"; 
 

 
document.write(oPerson);
<!DOCTYPE html> 
 
<html lang="en"> 
 

 
<head> 
 
    <meta charset="UTF-8"> 
 
    <title>Exercise - Personal Info</title> 
 
    <script src="practice9JS.js" type="text/javascript"></script> 
 
</head> 
 

 
<body> 
 
</body> 
 

 
</html>

+2

你的代碼工作 – sheplu

+0

需要顯示對象的內容作爲一個整體,以及 – Dale

+1

那麼是什麼所有人都在談論'無法執行「寫」上「Document''?問題是錯誤還是錯誤輸出?由於錯誤,我的意思是「不是你所期望的」,因爲打印的內容對你寫的代碼是正確的。 – csmckelvey

回答

1

你document.write()的調用exectuting作爲正在閱讀HTML。到DOM加載時,您的消息不再可見。試試這個:

setTimeout(() => document.write(oPerson.lastName), 1000); 
+0

它的工作原理顯示它到控制檯,但我試圖在網站上顯示它 – Dale

+0

@Dale如果你能'噸調整,你在做什麼編程? –

+0

它只是一個類練習,當顯示一個對象時,出於這些目的它需要在屏幕上。否則,我會 – Dale

0

建議不要使用document.write,因爲它必須在加載頁面之前執行。它也是在HTML地方執行的地方。因此,如果您的代碼將被添加到頁面的head,而不是body. If you wish to just add something to HTML, you can do it with document.appendChild`。在創建新元素的地方,提供一些必要的信息並將其附加到正文中。

例如https://codepen.io/msamsel/pen/zEMZXX?editors=1010

function printToBody(str) { 
    var par = document.createElement('p'); 
    par.innerText = str; 
    document.getElementsByTagName('body')[0].appendChild(par); 
} 

var oPerson = { 
    firstName: 'John', 
    lastName: 'Travis', 
    age: 22 
} 

printToBody(oPerson.firstName) 
printToBody(oPerson.lastName) 
printToBody(oPerson.age) 

如果你真的想用文件的寫入,然後從頭部移到腳本體。然後document.write應該在那裏執行。

0

我不確定你想要做什麼,但是如果只是發佈對象的內容而沒有任何格式,這可能適合你。

var oPerson = { 
 
    firstName: 'John', 
 
    lastName: 'Travis', 
 
    gender: 'Male', 
 
    age: 22, 
 
    district: 'Northshore', 
 
    hairColor: 'Brown', 
 
    hairLength: 'Short', 
 
    height: '6\'11"', 
 
    weight: '74kg', 
 
    martialStatus: 'Engaged' 
 
} 
 
var app = document.getElementById('app'); 
 
app.innerHTML = JSON.stringify(oPerson);
<div id="app"> 
 
</div>

+0

夠好哈哈。不想要言語和花括號,但它確定 – Dale