2016-11-01 31 views
0

我正在生成一些輸入,並向它們中的每個添加事件偵聽器,當我將注意力集中在每個值時如何增加值* 2?更改值並添加事件偵聽器

這裏是我已經有了:

for (var i = 0; i < 3; i++) { 
    var input = document.createElement("input"); 
    document.body.appendChild(input); 
    random = Math.floor((Math.random() * 100) + 1); 
    this.input.value = random; 
    input.addEventListener('focus', function(e) { 
    this.value += random * 2; 
    }) 
} 
+0

你已經附加了一些代碼,似乎是它的問題? – Itay

+2

你的意思是'this.value = this.value * 2;'? –

+0

是的,這就是我的意思,我的錯誤。 – Bybnovskiy

回答

1

inputvalue始終是一個字符串。當其任一操作數是字符串時,+執行字符串連接。

所以你要分析value使用它作爲一個數字:

for (var i = 0; i < 3; i++) { 
 
    var input = document.createElement("input"); 
 
    document.body.appendChild(input); 
 
    random = Math.floor((Math.random() * 100) + 1); 
 
    this.input.value = random; 
 
    input.addEventListener('focus', function(e) { 
 
    this.value = +this.value + random * 2; 
 
    }) 
 
}

在這方面,我使用+強迫this.value爲數字。其他選項有parseInt,parseFloatNumber

但是,你說

如何增加值* 2,當我專注於他們每個人

那不是你的代碼試圖這樣做。您的代碼嘗試將添加到random * 2的值。只要雙擊它,加倍:

for (var i = 0; i < 3; i++) { 
 
    var input = document.createElement("input"); 
 
    document.body.appendChild(input); 
 
    random = Math.floor((Math.random() * 100) + 1); 
 
    this.input.value = random; 
 
    input.addEventListener('focus', function(e) { 
 
    this.value = +this.value * 2; 
 
    }) 
 
}

目前我仍在使用+爲重點,但*將迫使其操作數數,所以this.value *= 2也將工作。

1
for (var i = 0; i < 3; i++) { 
    var input = document.createElement("input"); 
    document.body.appendChild(input); 
    random = Math.floor((Math.random() * 100) + 1); 
    this.input.value = random; 
    input.addEventListener('focus', function(e) { 
    this.value *= 2; 
    }) 
} 

我已經嘗試了上面的代碼它的工作對我來說

相關問題