2017-10-14 371 views
2

我有一個小的腳本,在給定的時間段內通過數字遞增數字。如果增加一個值++的作品,如果我想添加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>

+0

[如何通過向元素添加整數值來更改innerHtml可能的重複?](https://stackoverflow.com/questions/17264978/how-to-change-innerhtml-by-adding-a-integer-value元素) – Andreas

回答

2

您將數字附加到字符串。將您的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>

這樣你就不需要在每次迭代解析你的電話號碼。

+0

非常感謝 - 我認爲這是關於它的,但正如你所看到的,有人不得不讓我意識到這一點。我會在幾分鐘內說出你最好的。 – sauero

1

當您使用+它需要作爲串並連接爲一個字符串,使用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>

+0

你不覺得有一個重複的那裏,因爲這是一個非常簡單,可能經常問的問題? – Andreas

1

爲了保持邏輯清晰,只使用一個局部變量來存儲該值,無需向後經由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();