简体   繁体   English

为什么没有使用XMLHttpRequest从此XML文档中显示标题标签?

[英]Why don't the title tags display from this XML document with XMLHttpRequest?

I've downloaded this books.xml file from W3Schools, and I've parsed it with the code below ( with instructions from W3Schools ), but the title tags don't appear in the parsed code. 我已经从W3Schools下载了这个books.xml文件,并使用下面的代码( 根据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> 

How do I get the title tags to appear in the result too? 如何使标题标签也出现在结果中?

You are telling the browser to treat the XML as HTML … which it isn't. 您要告诉浏览器将XML视为HTML…事实并非如此。

Most of the elements in the XML do not exist in HTML so error recovery sticks them into the document with default styling. XML中的大多数元素都不存在于HTML中,因此错误恢复会将它们粘贴到具有默认样式的文档中。

HTML does have a <title> element. HTML确实具有<title>元素。 It controls the default bookmark name and is displayed in the browser's title bar and is used to label the tab (this may vary between browsers). 它控制默认的书签名称,并显示在浏览器的标题栏中,并用于标记标签(在不同的浏览器中可能有所不同)。 The <title> element isn't rendered in the document, so its default styling is display: none . <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> 

You would have to write CSS to change that if you wanted it to display. 如果要显示CSS,则必须编写CSS进行更改。

A better bet would be to read the data out of the XML and generate real, semantic HTML. 更好的选择是从XML中读取数据并生成真实的语义HTML。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM