[英]How to change title of page on .load() with new title of loaded page in jQuery
I'm confused about the .load()
and $.ajax
. 我对.load()
和$.ajax
感到困惑。 I have the following jQuery code in my index.html
: 我的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'));
})
and HTML: 和HTML:
<a href="test.html" class="load_ext">test</a>
In the example above, I'm loading partial content from the test.html
(the content of id #content_to_load
). 在上面的示例中,我正在从test.html
加载部分内容(ID为#content_to_load
的内容)。 I also want to grab the title of that test.html
page and replace the index.html
title page with that one. 我也想抓住那个test.html
页面的标题,并用那个替换index.html
标题页面。
I tried doing something like: 我尝试做类似的事情:
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'));
without any luck. 没有任何运气。 It gives me the current page title. 它给了我当前的页面标题。 How can I replace the title by doing something like: 我该如何通过以下方式替换标题:
$('title').text(newPageTitle);
Thanks! 谢谢!
EDIT: Thanks to @Jeff Schafer, @dystroy, and @zeroflagL I managed to solve this problem. 编辑:感谢@Jeff Schafer,@ dystroy和@zeroflagL,我设法解决了这个问题。 Here's the changed code: 这是更改后的代码:
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'));
The main problem with load
is that jQuery, when building the DOM fragment, strippes what isn't the body. load
的主要问题是,jQuery在构建DOM片段时会剥离不是正文的内容。 You can use this to get the title of a distant page : 您可以使用它来获取遥远页面的标题:
$.get(url, function(html){
var matches = html.match(/<title>([^<]*)/);
if (matches.length>0) {
var title = matches[1];
document.title = title;
}
});
Note that this won't work if the distant page is from a different origin and doesn't specifically allow cross-domain requests. 请注意,如果遥远的页面来自不同的来源并且不允许跨域请求,则此方法将无效。
You can get the title of the new page through the responseText: 您可以通过responseText获得新页面的标题:
.load(url + ' #content_to_load', function(responseText) {
repsonseText
is literally text, though, the source code of the page. repsonseText
实际上是文本,是页面的源代码。 You can use regular expressions, for instance, to extract the title of test.html
. 例如,您可以使用正则表达式提取test.html
的标题。 Then you can change the title with document.title = newTitle
. 然后,您可以使用document.title = newTitle
更改标题。
try this code to change page title 尝试使用此代码更改页面标题
document.title = newPageTitle;
hope it helps 希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.