【问题标题】:How to dynamically change document title via function?如何通过函数动态更改文档标题?
【发布时间】:2015-04-08 10:34:06
【问题描述】:

我想动态更改文档的标题。

首先我尝试了这个 sn-p:

var milis = 3000,
    titles = [
      'Setting up color scheme'
    ], count = 0;
    titles.push(document.title);
    setInterval(function(){
      document.title = titles[count % titles.length];
      ++count;
    }, milis);

这很好用,但我需要将 sn-p 放入一个函数中,以便随时附加标题。

函数长这样

function setUpTitle(){
    var milis = 3000;
    for(var i in arguments){
        titles = [
            arguments[i]
        ], count = 0;
        titles.push(document.title);
        setInterval(function(){
            document.title = titles[count % titles.length];
            ++count;
        }, milis);
    }
}

setUpTitle('one', 'two', 'three', ..., document.title);

但标题根本没有改变。

我该如何改变它?

【问题讨论】:

  • 尝试在titles数组后放置一个分号而不是逗号。 "];"
  • 还是不行。我这样做了:titles = [ arguments[i] ]; count = 0; 在那个函数中
  • 好的,如何将 for 循环更改为:for(var i = 0, j = arguments.length; i

标签: javascript jquery document title


【解决方案1】:

试试这个:

var currentTitle = document.title;

var beginSubmission = setInterval(function(){
    loaded+=1;
    bar.css('width', loaded+'%');

    document.title = loaded+'% :: ' + currentTitle;

    text.empty().append(loaded + "% completed. <br>");
    if (loaded >= 100){
        clearInterval(beginSubmission);
        text.html('Done');
        document.title = currentTitle;
    }
}, time);

这会备份您的标题并更改其上的百分比。最后,把原来的标题放回页面上。

另外,删除这个:

        var milis = 3000,
        titles = [
            'Setting up color scheme'
        ], count = 0;
        titles.push(document.title);
        title = setInterval(function(){
            document.title = titles[count % titles.length];
            ++count;
        }, milis);

或者替换成这个:

document.title = 'Setting up color scheme';

【讨论】:

    【解决方案2】:

    哦,你正在覆盖你的变量。试试这个:

    function setUpTitle(){
        var milis = 1000;
        var titles = [document.title];
        var count = 0;
        for(var i in arguments){
            titles.push(arguments[i]);
        }
        setInterval(function(){
            document.title = titles[count % titles.length];
            ++count;
        }, milis);
    }
    
    setUpTitle('one', 'two');
    

    http://jsfiddle.net/otow2fg8/1/

    【讨论】:

    • 第一次进入循环时,最后只显示一项,在我们的例子中:一(一,页面标题>二,一,页面标题>二,一...)
    • 请解释一下你的意思?它应该像:标题 -> 一 -> 二 -> 标题 -> 一 -> 二 -> ...尝试使用我编辑的答案。
    • 我的意思是:一-> 标题-> 二-> 一-> 标题-> (并不断重复二-> 一-> 标题)->... 我试过了!这就是我得到的。
    • IMO 您已将 setInterval() 函数复制到 for() 循环中。应该在外面。请检查。
    • 修改了,现在完美了!
    猜你喜欢
    • 2020-04-06
    • 2011-11-22
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-10
    • 2020-07-25
    • 1970-01-01
    相关资源
    最近更新 更多