繁体   English   中英

如何使用jQuery中新的已加载页面标题更改.load()上的页面标题

[英]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&#8230;</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&#8230;</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&#8230;</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.

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