[英]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.