添加数字,而不是增加增量
我有一个小的脚本,在给定的时间段内通过数字递增数字。如果增加一个值++的作品,如果我想添加math.random函数生成的另一个值而不是添加,请添加到现有值。我该如何改变这一点?我想要生成的数字添加到innerHTML中的现有值。添加数字,而不是增加增量
document.getElementById("data-gen").innerHTML = Math.floor((Math.random() * 100000) + 1) + Math.floor((Math.random() * 100) + 1);
nowResources = function() {
document.getElementById("data-gen").innerHTML += Math.floor((Math.random() * 10) + 1);
setTimeout(nowResources, 1000);
}
nowResources();
<span id="data-gen" style="color: #da5cb2;"></span>
您将数字附加到字符串。将您的innerHTML
转换成parseInt
的数字,它会按照您的预期工作。
document.getElementById("data-gen").innerText = Math.floor((Math.random() * 100000) + 1) + Math.floor((Math.random() * 100) + 1);
nowResources = function() {
// parseInt(yourString, radix)
const num = parseInt(document.getElementById("data-gen").innerText, 10);
document.getElementById("data-gen").innerText = num + Math.floor((Math.random() * 10) + 1);
setTimeout(nowResources, 1000);
}
nowResources();
<span id="data-gen" style="color: #da5cb2;"></span>
但一个缺点是,您要查询你想改变它,每次DOM。这是更好地保存你的电话号码你的超时之外,它的时间间隔是这样的:
let num = Math.floor((Math.random() * 100000) + 1) + Math.floor((Math.random() * 100) + 1);
document.getElementById("data-gen").innerText = num;
nowResources = function() {
num += Math.floor((Math.random() * 10) + 1);
document.getElementById("data-gen").innerText = num;
}
setInterval(nowResources, 1000);
nowResources();
<span id="data-gen" style="color: #da5cb2;"></span>
这样你就不需要在每次迭代解析你的电话号码。
非常感谢 - 我认为这是关于它的,但正如你所看到的,有人不得不让我意识到这一点。我会在几分钟内说出你最好的。 – sauero
当您使用+它需要作为串并连接为一个字符串,使用parseInt
document.getElementById("data-gen").innerHTML = parseInt(document.getElementById("data-gen").innerHTML) + (Math.floor((Math.random() * 10) + 1));
DEMO它转换为整数
document.getElementById("data-gen").innerHTML = Math.floor((Math.random() * 100000) + 1)+ Math.floor((Math.random() * 100) + 1);
nowResources = function() {
document.getElementById("data-gen").innerHTML = parseInt(document.getElementById("data-gen").innerHTML) + (Math.floor((Math.random() * 10) + 1));
setTimeout(nowResources, 1000);
}
nowResources();
<span id="data-gen" style="color: #da5cb2;"></span>
你不觉得有一个重复的那里,因为这是一个非常简单,可能经常问的问题? – Andreas
为了保持逻辑清晰,只使用一个局部变量来存储该值,无需向后经由parseInt
和疲倦(和昂贵的,并且杂乱)DOM元素方法跳舞转换:
var value = 0;
function setValue(addValue) {
value += addValue;
document.getElementById("data-gen").innerHTML = value;
}
nowResources = function() {
setValue(Math.floor((Math.random() * 10) + 1))
setTimeout(nowResources, 1000);
}
nowResources();
[如何通过向元素添加整数值来更改innerHtml可能的重复?](https://stackoverflow.com/questions/17264978/how-to-change-innerhtml-by-adding-a-integer-value元素) – Andreas