如何为<title>标签的部分内容提供ID?</title>

时间:2014-06-07 00:38:43

标签: javascript html

我的标题标签看起来像这样:

<title>My Page Title - Photo #3</title>

我想使用JavaScript来更改它的数字部分,而不必硬编码服务器端生成的“我的页面标题 - 照片#”字符串。

我尝试在一个范围内包装数字,以便我可以更改范围的内容:

<title>My Page Title - Photo #<span class="photoid">3</span></title>

但似乎title标记中不允许使用HTML。如果可能的话,我真的很想继续使用类方法,因为这样我就可以使用一行jquery:

$('.photoid').html(new_photoid);

我是否提到过photid出现在页面的几个地方,这就是为什么我希望能够使用这个oneliner同时更改它们的原因?例如:

<p>A paragraph also containing the number <span class="photoid">3</span></p>

5 个答案:

答案 0 :(得分:0)

标题只能包含文字,因此您需要解析它。

document.title = document.title.replace(/\d+$/, "new value");

答案 1 :(得分:0)

标题不能这样设置, 它不是.html的孩子

有点像

var num = 3;
document.title = "foo "+num

设置标题,然后为这些photoid重复使用num。

答案 2 :(得分:0)

使用jQuery onDocumentReady语法:

$(function () {
    var elements = $('.contains_photoid');
    elements.html(elements.html().replace("3", "4"));

    $(document).attr('title', $(document).attr('title').replace("3", "4"));
});

在此示例中,您无法看到标题更改,但这是语法。见Changing the page title with Jquery

"3""4"可以更改为任何内容,因此您可以创建具有唯一字符串的页面来代替真实ID,以便在文本中显示时可以轻松替换它数字已经存在。

http://jsfiddle.net/ZmXj5/1/

答案 3 :(得分:0)

<强>的Javascript

var photoID = 355; //this assumes you have some code where you set this photoID value
var title = document.title;
title = title.substr(0,title.lastIndexOf('#')+1);
document.title = title+photoID;

请参阅此小提琴以获取证据: http://jsfiddle.net/xrkhA/
(我使用了div内容,因为你不能在jsfiddle中使用title)

答案 4 :(得分:0)

您可以使用,但$(&#39;标题&#39;)将在IE8中失败

document.title="new title";

$('title').html('new title');  

$(document).attr('title','new title');