2013-03-13 57 views
2

我對​​和$.ajax感到困惑。我在我的index.html以下jQuery代碼:如何更改.load()頁面的標題,並在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:從test.html(標識#content_to_load的內容)

<a href="test.html" class="load_ext">test</a> 

在上面的例子中,我加載部分內容。我也想抓住那個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謝弗,@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')); 
+0

http://stackoverflow.com/questions/2115200/jquery-load-or-ajax-to-get-and-set-page-title – Dom 2013-03-13 14:37:43

+0

@Dom我試過,但他們使用'#title'編號來找到標題。我想要頁面的''。 – Alex 2013-03-13 14:39:15

+0

'嘗試在該.load.的回調中設置新的document.title。選定的答案。 – Dom 2013-03-13 14:39:50

回答

2

您可以通過responseText的獲取新頁面的標題:

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

repsonseText is litera lly文本,但是,頁面的源代碼。例如,您可以使用正則表達式來提取標題test.html。然後你可以改變標題document.title = newTitle

+0

downvotes爲一個正確的答案,有趣的 – zeroflagL 2013-03-13 15:01:36

+0

真棒。我使用這個來自dystroy的答案的正則表達式。是的,我不知道誰是瘋狂的低調。我給了你+1。 – Alex 2013-03-13 15:13:27

+0

謝謝亞歷克斯________ – zeroflagL 2013-03-13 15:16:10

1

試試這個代碼更改頁面標題

document.title = newPageTitle; 

希望它有助於

+0

反對的原因是什麼? – iJade 2013-03-13 14:37:42

+0

什麼是倒票?這是對的。 – 2013-03-13 14:38:29

+1

我想用我正在加載的頁面的標題替換標題 – Alex 2013-03-13 14:40:05

3

load的主要問題在於,jQuery在構建DOM片段時剝去了什麼不是主體。你可以用它來獲取一個遙遠的頁面的標題:

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

注意,如果遙遠的頁面是從不同的來源和不明確允許跨域請求,這將無法正常工作。

+1

謝謝你沒有發佈與其他人相同的答案。我把這個置於評論中,但似乎被忽略。 – 2013-03-13 14:52:50

+0

@dystroy:謝謝,夥計!它工作 – Alex 2013-03-13 14:57:16

+1

@JeffShaver這是一個很好的評論傑夫:)。我看到您的評論後刪除了我的答案。 – 2013-03-13 14:58:11

相關問題