jQuery: how to change title of document during .re

2020-01-24 20:03发布

I am using some nested layouts in Ruby on Rails, and in one of the layouts i have a need to read in a string from a div and set that as the title of the document. What is correct way (if any) to set the title of the document?

<script type="text/javascript">
$(document).ready(function() {

    // ???

});
</script>

8条回答
Emotional °昔
2楼-- · 2020-01-24 20:09

This works fine in all browser...

$(document).attr("title", "New Title");

Works in IE too

查看更多
Lonely孤独者°
3楼-- · 2020-01-24 20:16

The following should work but it wouldn't be SEO compatible. It's best to put the title in the title tag.

<script type="text/javascript">

    $(document).ready(function() {
        document.title = 'blah';
    });

</script>
查看更多
三岁会撩人
4楼-- · 2020-01-24 20:22

If you have got a serverside script get_title.php that echoes the current title session this works fine in jQuery:

$.get('get_title.php',function(*respons*){
    title=*respons* + 'whatever you want'   
    $(document).attr('title',title)
})
查看更多
forever°为你锁心
5楼-- · 2020-01-24 20:24

Like this:

$(document).ready(function ()
{
    document.title = "Hello World!";
});

Be sure to set a default-title if you want your site to be properly indexed by search-engines.

A little tip:

$(function ()
{
    // this is a shorthand for the whole document-ready thing
    // In my opinion, it's more readable 
});
查看更多
家丑人穷心不美
6楼-- · 2020-01-24 20:26

document.title was not working for me.

Here is another way to do it using JQuery

$('html head').find('title').text("My New Page Title");
查看更多
Explosion°爆炸
7楼-- · 2020-01-24 20:31

Do not use $('title').text('hi'), because IE doesn't support it.

It is better to use document.title = 'new title';

查看更多
登录 后发表回答