Javascript 如何为标记的部分内容提供ID?

Javascript 如何为标记的部分内容提供ID?,javascript,html,Javascript,Html,我有一个标题标签,看起来像这样: <title>My Page Title - Photo #3</title> 我有没有提到photoid出现在页面上的几个地方,这就是为什么我希望能够使用此oneliner同时更改它们?例如: <p>A paragraph also containing the number <span class="photoid">3</span></p> 标题只能包含文本,因此需要对其进行解析

我有一个标题标签,看起来像这样:

<title>My Page Title - Photo #3</title>
我有没有提到photoid出现在页面上的几个地方,这就是为什么我希望能够使用此oneliner同时更改它们?例如:

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

标题只能包含文本,因此需要对其进行解析

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

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

比如

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

要设置标题,请对这些照片ID重复使用num。

使用jQuery onDocumentReady语法:

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

    $(document).attr('title', $(document).attr('title').replace("3", "4"));
});
在本例中,您看不到标题的更改,但这就是语法。看

3和4可以更改为任何内容,因此您可以使用唯一的字符串来代替真实ID创建页面,以便在文本中出现数字时轻松替换

Javascript

看这把小提琴来证明:
我使用了div内容,因为您不能在jsfiddle中使用title,您可以使用,但在IE8中,$'title'将失败

document.title="new title";


那么,你的标题中有数字,还有其他元素中也有数字,即你的标题中没有标签,是吗???@JustcallmeDrago:正确,用一个例子说明。等等,你是在问关于或关于元素的问题吗?如果您只想在中使用常规元素,那么您的代码有什么问题?你试过了吗?真的没有理由使用。准备好设置标题了。我把它扔进去了,因为这比不使用更接近于同时更改所有事件。我明白了。我错过了你同时设置其他元素的机会。最后是vallina JS解决方案。
$(function () {
    var elements = $('.contains_photoid');
    elements.html(elements.html().replace("3", "4"));

    $(document).attr('title', $(document).attr('title').replace("3", "4"));
});
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;
document.title="new title";
$('title').html('new title');  
$(document).attr('title','new title');