javascript - 为什么使用 XMLHttpRequest 不显示此 XML 文档的标题标签?

标签 javascript html xml xml-parsing

我已经下载了这个books.xml来自 W3Schools 的文件,我已使用下面的代码对其进行了解析 ( 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>

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

最佳答案

您告诉浏览器将 XML 视为 HTML……但事实并非如此。

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

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

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

如果您希望它显示,您必须编写 CSS 来更改它。

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

关于javascript - 为什么使用 XMLHttpRequest 不显示此 XML 文档的标题标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44750290/

相关文章:

javascript - 从购物车中删除在 AngularJS 中不起作用

javascript - AngularJS 过滤器不起作用

javascript - 如何向 nvd3 饼图添加 tabindex 属性?

jQuery 警报正在返回代码

php - 将特殊字符 '&' 、 '>' 和 '<' 转换为其各自的 XML 字符引用

XML 解析错误 : not well-formed

javascript - 使用 Javascript 的递归问题

javascript - 为什么在按下其他按钮后 'click' 函数在 jQuery 中不起作用?

python - 如何使用beautifulsoup获取html中的类内容?

xml - 创建不带结束标记的 XML 元素