繁体   English   中英

从HTML将变量传递给JS函数

[英]Passing on a variable to a JS function from HTML

我目前正在为学校编写一些编程任务。 我之所以选择该任务,是因为我对如何使程序的核心运行在Java上有了一个想法,但是我在将其转换为一个非常简单的Web页面(没有使用HTML或JS的经验)时遇到了问题。

我的问题是:我正在通过按钮接收输入。 单击时,将调用一个函数,该函数将获取输入的值。 但是,我得到的所有警告窗口都是objectHTMLinputElement。 我究竟做错了什么?

 function myRT() { var risikoTraeger=document.getElementById('input1').value; } function myRH() { var risikoHoehe = parseInt(document.getElementById('input2')).value; alert(input2); } 
 <h1>Siemens: Risikoassessment</h1> <p id="demo">How many entries?</p> <input type="text" id="input1" /> <button type="button" onclick="myRT()">Risk carrier</button> <input type="text" id="input2" /> <button type="button" onclick="myRH()">Sum of the risk</button> 

在解析之前获取输入的值。 另外,您正在警告输入元素,而不是将值设置为变量。 采用:

function myRH(){
  var risikoHoehe = parseInt(document.getElementById('input2').value);
  alert(risikoHoehe);
}

更改此部分parseInt(document.getElementById('input2')).value; 如下:

parseInt(document.getElementById('input2').value)

您输入了错误的变量,请尝试使用“ risikoHoehe”而不是“ input2”:

function myRT() {
  var risikoTraeger=document.getElementById('input1').value; 
}

function myRH(){
  var risikoHoehe = document.getElementById('input2').value;
  alert(risikoHoehe);
}

1)您正在尝试将DOM元素解析为一个int以便它返回undefined

使用document.getElementById('input2').value

2)仅在需要时使用parseInt,如果仅用于警告,则可以跳过它

3)您不能直接通过id引用dom元素,您必须在变量中获取该元素然后使用它。

alert(input2); 应该alert(risikoHoehe);

好,这是完整的工作代码-

 <!DOCTYPE html> <html> <head> <script type="text/javascript"> function myRT() { var risikoTraeger=document.getElementById('input1').value; alert(risikoTraeger); } function myRH(){ var risikoHoehe = parseInt(document.getElementById('input2').value); alert(risikoHoehe); } </script> </head> <body> <h1>Siemens: Risikoassessment</h1> <p id="demo">How many entries?</p> <input type="text" id="input1" /> <button type="button" onclick="myRT()">Risk carrier</button> </br> <input type="text" id="input2" /> <button type="button" onclick="myRH()">Sum of the risk</button> </body> </html> 

希望这对您有帮助:)

让我们看看您在做什么错:

var risikoHoehe = parseInt(document.getElementById('input2')).value;

文献
文件本身
getElementById()
给我们提供具有特定ID参数的元素的函数
'input2'
所需输入的ID
。值
元素的值(如果有)。
parseInt()
将任何字符串转换为整数值的函数。

现在看这里:

  • document.getElementById('input2') =>输入元素本身(objectHTMLInputElement)

  • parseInt(objectHTMLInputElement) =>如果尝试将html输入元素转换为整数,会得到什么?

  • (整数).value =>整数是否具有value属性?

但是,如果您这样编写:

var risikoHoehe = parseInt(document.getElementById('input2').value);
  • document.getElementById('input2') =>输入元素本身(objectHTMLInputElement)

  • objectHTMLInputElement.value =>输入值作为字符串

  • parseInt(string) =>解析字符串的整数值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM