2017-09-10 137 views
0

因此,如果我有多個HTML文件連接到一個JS文件,當我運行使用document關鍵字的代碼時,代碼是否知道我指的是哪個文檔?例如,在其中一個HTML文件中,我有一個div,在body標籤和js文件中有main的id,我創建了一個新的div來追加到特定的html文件。 js文件中的代碼基本上是var div = document.createElement(「div」),接着是document.getElementById(「main」)。appendChild(div)。我的問題基本上是,當我使用getelementbyid時,代碼是否知道要將div附加到哪個html文件以及要使用哪個html文件?如果沒有,如果我有多個html文件連接到一個js文件,我該如何指定這個?連接到一個JS文件的多個HTML文件?

+0

你可能必須爲每個HTML的div指定不同的ID,以便它可以決定。 –

+0

如果您將問題更改爲「在多個HTML文件中使用相同的.js」,那麼它會更好地理解(對您) –

回答

0

只要您指定要更改的div的ID,它應該可以工作。

JS的可能是這樣的:

var div1 = document.createElement("div") 
document.getElementById("id1").appendChild(div1); //matches to div1 in the html 

var div2 = document.createElement("div"); 
document.getElementById("id2").appendChild(div2). //matches to div2 in the html 

var div3 = document.createElement("div") 
document.getElementById("id3").appendChild(div3). //matches to div3 in the html 

的HTML可能是這樣的:

<div id="id1"></div> 

<div id="id2"></div> 

<div id="id3"></div>