1

我目前正在使用...

$(function () { 
    var title = document.title; 
    var count = $('.div').length; 
    $(this).attr("title", title + ' (' + count + ') ' + ' - Category Page');
});

...在页面标题中添加一个数字。使用这种方法只允许我在 'count' + - 之后的任何内容都具有相同的措辞。

我将如何改变这一点,以便在 HTML 标题标签中,我可以拥有 - 类别页面,或任何内联,并且只在连字符之前由 jquery 插入数字?

现在的 HTML ...

<title>Bicycles</title>

我想要什么...

<title>Bicycles - Category Page</title>

然后让 jquery 在连字符之前添加 div 计数。

4

3 回答 3

1

最后,这将取决于您,并且没有真正的标准可以遵循。这完全取决于您决定如何清理标题的内容。比如决定它是否来自服务器端,是否是硬编码的,等等。我说擦洗你的内容以获得标题,因为为了插入这个数字,你必须有某种占位符。()也许使用然后定位它是有意义的。也许你会使用_count_. 这就是实施取决于您和您的代码的地方。它必须是这种方式,因为您将在字符串内部进行搜索。

$(function () { //if you were inserting count into ()
 var title = document.title;
 var count = $('.div').length; 
 var ind = title.indexOf("()");
 title = title.substr(0,ind+1) + count + title.substr(ind+2,title.length);
 $(this).attr("title", title);
});

另一种方法是跟踪上面提到的两个子字符串。即前缀和后缀。这样你就可以做一些更简单的事情。

$(function () {
 var prefix = "Some Title";
 var suffix = "Category";
 var count = $('.div').length; 
 $(this).attr("title", prefix + ' (' + count + ') ' + ' - ' + suffix);
});
于 2013-04-09T19:02:51.110 回答
0

使用sprintf带有链接和解释说明的问题)。请注意,它不在标准 javascript 库中,而是在扩展中。

就像是

<!--in the title-->
<title>There are %d rabbits in the basket</title>

$(function () { 
    var title = document.title; 
    var count = $('.div').length; 
    $(this).attr("title", sprintf(title, count));
});
于 2013-04-09T19:00:40.917 回答
0

尝试

$(function () { 
    var title = document.title; 
    var count = $('.div').length;

    document.title = title + "( " + count + " ) - Category Page"; 
});
于 2013-04-09T19:01:31.683 回答