【问题标题】:document.getElementById does not capture the value [duplicate]document.getElementById 不捕获值 [重复]
【发布时间】:2021-10-14 11:21:56
【问题描述】:

我试图获取输入“numLineas”的值,但它不起作用。我做错了什么?

这里我给你代码:

var nLineas = parseInt(document.getElementById("numLineas").value);

function prueba(){ 

    window.alert(nLineas);

}
<form action=""> 
    <label for="numLineas">Con cuantas lineas deseas dibujar la curva?</label><br>
    <input type="text" id="numLineas"><br>
</form>
<br>
<button type="button" onclick="prueba()">Ingresar</button> 
<br>
   
<!--<script src="practica7_CurvaPersonalizada.js"></script>-->

在警报中只出现 NaN,无论我在那里写什么(数字或字符串)。请帮忙!

【问题讨论】:

  • @Spectric,很棒的编辑!
  • window.alert("nLineas"); 给你NaN 而不是nLineas
  • 您的 javacript 与 HTML 相关的位置在哪里?如果它在标记之上,你就会遇到这个问题。
  • @seesharper OP 表示它在标记之下
  • var nLineas...移入 prueba 函数并使用alert(nLineas),而不是alert("nLineas")

标签: javascript html


【解决方案1】:

这里有几点:

  • var nLineas = document.getElementById("numLineas").value; 应该放在 'onclick' 方法中,以更好地表明它是基于每次点击读取的。

  • 在调用parseInt之前,使用方法isNaN验证你正在读取的值是一个int

  • 使用document.getElementById().onclick=prueba 可以更好地为我分配该元素的功能。

  • window.alert("nLineas"); 只会返回nLineas。要获取您设置的变量的值,请使用不带引号的变量,例如console.log(nLineas)

document.getElementById("button").onclick = prueba;

function prueba() {
  var nLineas = document.getElementById("numLineas").value;
  if (!isNaN(nLineas)) {
    console.log("nLineas is a int");
    nLineas = parseInt(nLineas);
  }
  console.log("nLineas is " + nLineas);
}
<form action="">
  <label for="numLineas">Con cuantas lineas deseas dibujar la curva?</label><br>
  <input type="text" value="test" id="numLineas"><br>
</form>
<br>
<button id="button" type="button">Ingresar</button>
<br>
<script src="practica7_CurvaPersonalizada.js"></script>

【讨论】:

  • addEventListener() 优于直接分配onclick
  • @Phil 我会死在onclick = 山上。在 C# 中使用 += 分配点击处理程序后,我养成了这个习惯
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-22
  • 2014-07-18
  • 2018-06-29
  • 2011-11-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多