更改值并添加事件侦听器

时间:2016-11-01 09:35:02

标签: javascript html

我正在生成一些输入,并为每个输入添加事件监听器,当我关注每个输入时,如何增加值* 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;
  })
}

2 个答案:

答案 0 :(得分:1)

value的{​​{1}}始终是一个字符串。 input当其任一操作数是字符串时,它会进行字符串连接。

因此,您需要解析+以将其用作数字:

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.valueparseIntparseFloat

然而,你说过

  

当我专注于每个人时,如何增加值* 2

这不是你的代码试图做的。您的代码尝试添加 Number到该值。要加倍,加倍:

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; }) }进行强调,但+会将其操作数强制转换为数字,因此*也可以使用。

答案 1 :(得分: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;
  })
}
  

我已经尝试过上面的代码,它正在为我工​​作

相关问题