2017-09-10 139 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>