[英]How to change title of page on .load() with new title of loaded page in jQuery
我对.load()
和$.ajax
感到困惑。 我的index.html
包含以下jQuery代码:
$('.load_ext').click(function(e) {
var url = $(this).attr("href");
parentContainer.append($(document.createElement("div")).load(url + ' #content_to_load').html('<p class="loading">Loading…</p>').hide().fadeIn('slow'));
})
和HTML:
<a href="test.html" class="load_ext">test</a>
在上面的示例中,我正在从test.html
加载部分内容(ID为#content_to_load
的内容)。 我也想抓住那个test.html
页面的标题,并用那个替换index.html
标题页面。
我尝试做类似的事情:
var url = $(this).attr("href");
parentContainer.append($(document.createElement("div")).load(url + ' #content_to_load', function() {
console.log($(document).attr('title'));
}).html('<p class="loading">Loading…</p>').hide().fadeIn('slow'));
没有任何运气。 它给了我当前的页面标题。 我该如何通过以下方式替换标题:
$('title').text(newPageTitle);
谢谢!
编辑:感谢@Jeff Schafer,@ dystroy和@zeroflagL,我设法解决了这个问题。 这是更改后的代码:
var url = $(this).attr("href");
parentContainer.append($(document.createElement("div")).load(url + ' #content_to_load', function(responseText) {
var title = responseText.match(/<title>([^<]*)/)[1];
document.title = title;
}).html('<p class="loading">Loading…</p>').hide().fadeIn('slow'));
load
的主要问题是,jQuery在构建DOM片段时会剥离不是正文的内容。 您可以使用它来获取遥远页面的标题:
$.get(url, function(html){
var matches = html.match(/<title>([^<]*)/);
if (matches.length>0) {
var title = matches[1];
document.title = title;
}
});
请注意,如果遥远的页面来自不同的来源并且不允许跨域请求,则此方法将无效。
您可以通过responseText获得新页面的标题:
.load(url + ' #content_to_load', function(responseText) {
repsonseText
实际上是文本,是页面的源代码。 例如,您可以使用正则表达式提取test.html
的标题。 然后,您可以使用document.title = newTitle
更改标题。
尝试使用此代码更改页面标题
document.title = newPageTitle;
希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.