【问题标题】:getElementById(x).value changes the output depending on the context [duplicate]getElementById(x).value 根据上下文更改输出[重复]
【发布时间】:2021-10-21 05:02:23
【问题描述】:

我注意到插入在 javascript 中使用的数字输入数字字段中的数字在输出中具有不同的值,具体取决于它的调用方式。 在我的 sn-p 中,您可以清楚地看到调用 getElementById($number_input).value 在控制台中总是返回 NaN。相反,如果我分配给变量numb = getElementById($number_input),然后通过变量numb.value 调用该值,则控制台返回正确的数字。 我不明白为什么当这两种方法应该是相同的,或者至少对我来说应该是相同的时候,javascript会给出不同的结果。

提前谢谢你。

const number = document.getElementById("number").value; // will not give the expected value later on
const numberCorrect = document.getElementById("number"); // will give the expected value later on
const calculateInput = document.getElementById("calculate");

calculateInput.addEventListener("click", function() {
  let numb = parseInt(number);
  let numbCorrect = parseInt(numberCorrect.value);
  console.log(numb); // doesn't give the expected value: returns always NaN
  console.log(numbCorrect); // gives the expected value
})
<h2>Number</h2>
<input type="number" id="number" placeholder="Insert a number">
<input type="button" value="Calculate" id="calculate">

【问题讨论】:

标签: javascript


【解决方案1】:

当你这样做时

const number = document.getElementById("number").value; // will not give the expected value later on

你得到的是输入的初始值,它是空的,所以你得到一个""字符串。

然后,当将其解析为整数时,您会得到 NaN,因为 "" 不能是数字


相反,当做

const numberCorrect = document.getElementById("number"); // will give the expected value later on

您正在获得对输入的引用。因此,当您在其上键入内容时,引用将是相同的,调用 parseInt(numberCorrect.value) 将为您提供输入的当前值。

【讨论】:

    【解决方案2】:

    “number”是最初创建输入元素时的变量。所以它是“NaN”。

    “numberCorrect”是元素。

    当输入元素的值改变时,“numberCorrect.value”也改变了,“number”没有改变。

    因此显示“NaN”和当前值。

    【讨论】:

      猜你喜欢
      • 2014-08-04
      • 2021-09-14
      • 2011-02-17
      • 1970-01-01
      • 1970-01-01
      • 2019-10-26
      • 1970-01-01
      • 2021-10-24
      • 2015-04-20
      相关资源
      最近更新 更多