2

我对.load()and感到困惑$.ajax。我的 jQuery 代码如下index.html

$('.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'));
4

3 回答 3

3

主要问题load是 jQuery 在构建 DOM 片段时会剥离不是主体的内容。您可以使用它来获取远程页面的标题:

$.get(url, function(html){
    var matches = html.match(/<title>([^<]*)/);
    if (matches.length>0) {
        var title = matches[1];
        document.title = title;
    }
});

请注意,如果远程页面来自不同的来源并且不明确允许跨域请求,这将不起作用。

于 2013-03-13T14:50:44.720 回答
2

可以通过responseText获取新页面的标题:

.load(url + ' #content_to_load', function(responseText) {

repsonseText字面意思是文本,但是,页面的源代码。例如,您可以使用正则表达式来提取test.html. 然后您可以使用 更改标题document.title = newTitle

于 2013-03-13T14:50:35.487 回答
1

试试这个代码来改变页面标题

document.title = newPageTitle;

希望能帮助到你

于 2013-03-13T14:36:36.510 回答