如果你有:
var something = $('.element').text();
// something = 'The tortoise ran 5 times faster than the fox.';
有没有办法可以编辑它以将“5”更改为新var中的不同数字?所以我得到了
newSomething = 'The tortoise ran 6 times faster than the fox.';
注意:var中的数字是动态的,可以是0 - >之间的任何数字。 100,我需要将它递增1,我需要动态增加它(我不能将数字分配给var,因为它来自文档加载并被分配)
答案 0 :(得分:7)
var something = $('.element').text();
var newSomething = something.replace(/\d+/, function(match) {
return (Number(match) + 1).toString();
});
有关正在发生的事情的一些信息:代码使用更复杂的str.replace
函数形式。普通形式只需要两个字符串,并用第二个字符串替换第一个字符串的任何出现。
str.replace
还可以regular expression搜索(在这种情况下,\d+
,这意味着“一个或多个数字”),以及替换函数,因为我'在这里使用。我使用了一个匿名函数表达式,它接受一个参数match
。每个匹配都会调用此函数,因此如果您的字符串有多个匹配项,则会多次运行。
在函数中,匹配(字符串)正在转换为数字,递增,然后转换回字符串。然后,这将作为匹配替换器的结果返回。
答案 1 :(得分:1)
定义var ...
var num = 5;
var something = 'The tortoise ran ' + num + ' times faster than the fox.';
function whatever(){
num++;
something = 'The tortoise ran ' + num + ' times faster than the fox.';
}
答案 2 :(得分:1)
如何在php中包裹数字范围,以便您可以使用javascript轻松访问它:
<强> HTML 强>
<span class="element">The tortoise ran <span class="number">6</span> times faster than the fox.</span>
然后使用javascript,您可以轻松访问该号码:
Javascript
var number = Number($('.number').text());
$('.number').text(number + 1);
<强> Demo 强>