【问题标题】:Why don't the title tags display from this XML document with XMLHttpRequest?为什么这个带有 XMLHttpRequest 的 XML 文档中的标题标签不显示?
【发布时间】:2017-06-25 20:25:40
【问题描述】:

我从 W3Schools 下载了这个 books.xml 文件,并使用下面的代码 (with instructions from W3Schools) 对其进行了解析,但标题标签未出现在解析的代码中。

<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Required meta tags always come first -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <title></title>
</head>
<body>

  <p id="demo"></p>

<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("demo").innerHTML =
    this.responseText;
    console.log("Up to this line works.");
  }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
</script>
</body>
</html>

如何让标题标签也出现在结果中?

【问题讨论】:

标签: javascript html xml xml-parsing


【解决方案1】:

您是在告诉浏览器将 XML 视为 HTML ......它不是。

XML 中的大多数元素在 HTML 中不存在,因此错误恢复会将它们以默认样式粘贴到文档中。

HTML 确实有一个 &lt;title&gt; 元素。它控制默认书签名称并显示在浏览器的标题栏中并用于标记选项卡(这可能因浏览器而异)。 &lt;title&gt; 元素未在文档中呈现,因此其默认样式为 display: none

var style = window.getComputedStyle(document.querySelector("div title"));
console.log(style.getPropertyValue("display"));
&lt;div&gt;This is an invalid &lt;title&gt;title&lt;/title&gt; element.&lt;/div&gt;

如果你想让它显示,你必须编写 CSS 来改变它。

更好的选择是从 XML 中读取数据并生成真实的语义 HTML。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    相关资源
    最近更新 更多