![](/img/trans.png)
[英]How to write a single Jquery function to trigger on document change and ready events
[英]jQuery: how to change title of document during .ready()?
我在Ruby on Rails中使用了一些嵌套布局,在其中一个布局中,我需要读取div中的字符串并将其设置为文档的标题。 设置文档标题的正确方法是什么(如果有的话)?
<script type="text/javascript">
$(document).ready(function() {
// ???
});
</script>
以下应该可以工作,但它不会与SEO兼容。 最好将标题放在标题标签中。
<script type="text/javascript">
$(document).ready(function() {
document.title = 'blah';
});
</script>
不要使用$('title').text('hi')
,因为IE不支持它。
最好使用document.title = 'new title';
这适用于所有浏览器......
$(document).attr("title", "New Title");
也适用于IE
像这样:
$(document).ready(function ()
{
document.title = "Hello World!";
});
如果您希望您的网站被搜索引擎正确编入索引,请务必设置默认标题。
小提示:
$(function ()
{
// this is a shorthand for the whole document-ready thing
// In my opinion, it's more readable
});
<script type="text/javascript">
$(document).ready(function() {
$(this).attr("title", "sometitle");
});
</script>
document.title不适合我。
这是使用JQuery实现它的另一种方法
$('html head').find('title').text("My New Page Title");
我在Ruby on Rails中使用了一些嵌套布局,在其中一个布局中,我需要读取div中的字符串并将其设置为文档的标题。
正确的方法是在服务器端。
在你的布局中,在某些时候会有一些代码将文本放在div中 。 让这段代码也设置一些实例变量,比如@page_title
,然后在你的外部布局中让它做<%= @page_title || 'Default Title' %>
<%= @page_title || 'Default Title' %>
如果你有一个服务器端脚本get_title.php回应当前的标题会话,这在jQuery中工作正常:
$.get('get_title.php',function(*respons*){
title=*respons* + 'whatever you want'
$(document).attr('title',title)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.