Javascript setAttribute无法正常工作

时间:2018-05-11 16:29:40

标签: javascript html

我试图实现w3schools提供的includeHTML()函数。

https://www.w3schools.com/howto/howto_html_include.asp

如果我手动创建div,它可以正常工作,就像在网站中一样:

<div w3-include-html="awebsite.html"></div>

但是,如果我尝试使用Javascript创建div,则它无法正常工作,例如:

var htmlIncluder = document.createElement("div");
htmlIncluder.setAttribute("w3-include-html", "awebsite.html");
document.body.appendChild(htmlIncluder);

是否因为div默认没有w3-include-html属性?我应该怎么做才能使这项工作?

感谢您的帮助!

更新,这是我的index.html,为了更清楚地显示出现的顺序,它还显示了includeHTML功能:

<script>
function includeHTML() {
  var z, i, elmnt, file, xhttp;
  /*loop through a collection of all HTML elements:*/
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    elmnt = z[i];
    /*search for elements with a certain atrribute:*/
    file = elmnt.getAttribute("w3-include-html");
    if (file) {
      /*make an HTTP request using the attribute value as the file name:*/
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
          if (this.status == 200) {elmnt.innerHTML = this.responseText;}
          if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
          /*remove the attribute, and call this function once more:*/
          elmnt.removeAttribute("w3-include-html");
          includeHTML();
        }
      }
      xhttp.open("GET", file, true);
      xhttp.send();
      /*exit the function:*/
      return;
    }
  }
}
</script>
</head>
<body>
<!--this is the manually created div that works-->
<div w3-include-html="2.html"></div>
<!-- divs created with js.js have the correct attribute but don't show any content -->
<script src="js.js"></script>
<script>
includeHTML();
</script>
</body>

这里是js.js创建应该包含includeHTML()的div的部分;内容。将div添加到添加到网格的单元格中,并将整个内容添加到document.body中。它在网站上可见,所以它是正确的,例如文本元素&#34; middle&#34;是可见的。页面分为标题,中间和页脚作为网格,所有这些也是可见的。

cell.className = "middle";
cell.id = "middle-"+cellIdNo;
var text = document.createTextNode("middle");
var htmlIncluder = document.createElement("div");
htmlIncluder.setAttribute("w3-include-html", "2.html");
cell.appendChild(text);
cell.appendChild(htmlIncluder);

1 个答案:

答案 0 :(得分:0)

通过将includeHTML函数从index.html移动到我的js.js文件来实现它。并在window.onload = function(){}中添加了这段代码:

if( document.readyState === 'complete' ) {
    includeHTML();
}

现在它在创建div时调用该函数。仍然不知道为什么它没有从index.html起作用。