innerHTML在控制台中工作,但不在js文件中

时间:2018-02-16 21:05:16

标签: javascript html console innerhtml pre

我有这段代码:

window.addEventListener("load", function() {
 console.log("s");
 var pres = document.querySelectorAll("pre[lang]");
 console.log(pres);
 for (var i = 0; i < pres.length; i++) {
  console.log("x")
  var lang = pres[i].getAttribute("lang");
  console.log(lang);
  console.log(pres[i].innerHTML);
  pres[i].innerHTML = highlight_c(pres[i].innerHTML);
  console.log(pres[i].innerHTML);
}
});

除了console.log之外,所有console.log(pres[i].innerHTML);都有效。 pres[i].innerHTML = highlight_c(pres[i].innerHTML);也无效。但它确实在控制台中工作。当我在JavaScript控制台中运行此代码时,一切正常!但是当它从js文件运行时,它不起作用。

顺便说一句:那些凌乱的console.log只是检查我的代码是否正在运行。

编辑highlight_c函数在另一个文件中定义,并且完全正常。

这是我的HTML:

<html>
<head>
  <title>Index - C: Local documentation</title>
  <link rel="stylesheet" type="text/css" href="styles/global.css">
  <link rel="stylesheet" type="text/css" href="syntax-highlighting/styles/c.css">
  <meta charset="utf-8">
</head>
<body>
  <div id="container">
    <div id="header">
      <h1>C: Local documentation</h1>
    </div>
    <div id="content">
      <div id="nav">
        <h3>Navigation</h3>
        <ul>
          <li><a href="reading-files.html" class="selected">Reading files</a></li>
          <li><a href="page02.html">Page 02</a></li>
          <li><a href="page03.html">Page 03</a></li>
        </ul>
      </div>
      <div id="main">
        <h2>Reading files</h2>
        <p>How to read files:</p>
        <pre lang="c" src="reading-files.c"></pre>
        <p>That's it.</p>
      </div>
    </div>
    <div id="footer">
      Copyright &copy; 2018 Quintus Rijpstra.
    </div>
  </div>
  <script type="text/javascript" src="scripts/pre-load.js"></script>
  <script type="text/javascript" src="syntax-highlighting/load.js"></script>
  <script type="text/javascript" src="syntax-highlighting/scripts/c.js"></script>
</body>

pre标记没有内容,只有src标记,其他函数使用该标记将文本加载到其中:

window.addEventListener("load", function() {
var pres = document.querySelectorAll("pre[src]");
for (var i = 0; i < pres.length; i++) {
  var src = pres[i].getAttribute("src");
  loadfile(src, load);
}
});

function load(filecontent, filename) {
var pre = document.querySelectorAll("pre[src=\"" + filename + "\"]");
for (var i = 0; i < pre.length; i++) {
  pre[i].innerHTML = filecontent;
}
}

function loadfile(filename, handler) {
var xmlrequest = new XMLHttpRequest();
xmlrequest.open("GET", filename);
xmlrequest.onreadystatechange = function() {
  if (xmlrequest.readyState == 4) {
    if (xmlrequest.status == 200) {
      var content = xmlrequest.responseText;
      handler.call(null, content, filename);
    }
  }
};
xmlrequest.send(null);
}

任何人都可以帮助我吗? 提前谢谢!

1 个答案:

答案 0 :(得分:0)

而不是

var pres = document.querySelectorAll("pre[lang]");

尝试让你的前期&#39; JS中标记名称的标记:

var pres = document.getElementsByTagName('pre')[lang].innerHTML;