【问题标题】:Multiple HTML files connected to one JS file?多个 HTML 文件连接到一个 JS 文件?
【发布时间】:2018-02-18 13:56:40
【问题描述】:

所以如果我有多个 HTML 文件连接到一个 JS 文件,当我运行使用 document 关键字的代码时,代码是否知道我指的是哪个文档?例如,在其中一个 HTML 文件中,我在 body 标记中有一个 id 为 main 的 div,在 js 文件中,我创建了一个新的 div 以附加到该特定的 html 文件。 js 文件中的代码基本上是 var div = document.createElement("div") 后跟 document.getElementById("main").appendChild(div)。我的问题基本上是,当我使用 getelementbyid 时,代码是否知道将 div 附加到哪个 html 文件以及使用哪个 html 文件?如果没有,如果我有多个html文件连接到一个js文件,我该如何指定?

【问题讨论】:

  • 您可能必须为每个 HTML div 指定不同的 id,以便它可以决定。
  • 如果您将问题更改为“在多个 HTML 文件中使用相同的 .js”,那么(对您而言)会更好理解

标签: javascript


【解决方案1】:

只要您指定要更改的 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多