jQuery 将外部 html 页面 <title> 插入另一个 html 页面
jQuery Insert external html page <title> into another html page
我有两个文件 index.html 和 index2.html。这两个文件都在本地计算机上的同一目录中(无法访问 PHP,等等)。
我正在尝试
<title>Page Title</title>
来自 index.html 并使用 jQuery 将其插入 index2.html 中的 div.content。在 index2.html 我有:
$('.content').load("index.html title");
我尝试使用 jQuery .load() 但它不起作用,我看到 documentation 状态:
"jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as <html>, <title>, or <head> elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser."
如何使用 jQuery 从 index.html 检索标题并将其放置在 index2.html 中的 div.content 中?
我想你想试试 .get
方法:
$.get("index2.html", function( my_var ) {
var title = $(my_var).filter('title').text();
//title contains the title of index2.html
});
请注意,这仅适用于同一域。如果您使用 'get' 调用不受您控制的外部域,您将收到 CORS 错误。
此外,这似乎不是执行此操作的最佳方式,因为您基本上是在加载另一个 HTML 页面。不确定您的性能目标是什么,但我可能会想到另一种方法来检索标题。
我有两个文件 index.html 和 index2.html。这两个文件都在本地计算机上的同一目录中(无法访问 PHP,等等)。
我正在尝试
<title>Page Title</title>
来自 index.html 并使用 jQuery 将其插入 index2.html 中的 div.content。在 index2.html 我有:
$('.content').load("index.html title");
我尝试使用 jQuery .load() 但它不起作用,我看到 documentation 状态:
"jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as <html>, <title>, or <head> elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser."
如何使用 jQuery 从 index.html 检索标题并将其放置在 index2.html 中的 div.content 中?
我想你想试试 .get
方法:
$.get("index2.html", function( my_var ) {
var title = $(my_var).filter('title').text();
//title contains the title of index2.html
});
请注意,这仅适用于同一域。如果您使用 'get' 调用不受您控制的外部域,您将收到 CORS 错误。
此外,这似乎不是执行此操作的最佳方式,因为您基本上是在加载另一个 HTML 页面。不确定您的性能目标是什么,但我可能会想到另一种方法来检索标题。