gpt4 book ai didi

javascript - 将输入值传递给 JavaScript 函数

转载 作者:行者123 更新时间:2023-12-01 03:40:46 25 4
gpt4 key购买 nike

我在将输入值传递到 JavaScript 函数时遇到问题,该函数需要两个值并将它们相乘。当我硬编码我的数字时,它工作得很好。但是,当我尝试使用输入值时,我什么也没有得到——甚至没有得到undefined。这是我的代码:

function multiply (val1, val2) {
var n = val1;
for(var i = 1; i < val2; i++) {
n += val1;
}
return n;
}

var result = multiply(document.getElementById('first').value, document.getElementById('second').value);

document.getElementById('result').innerHTML = result;
<h1>Mutiplication Algorithm</h1>

<p>This algorithm attempts to multiply to given values without ever using the <span>*</span> operator</p>

<input id="first" type="text" value=5 /> x
<input type="text" value=4 /> =
<span id="result"></span>

谢谢!

最佳答案

请再次检查您的代码。您没有第二个输入 id 参数。然后,如果您想将值视为整数,只需将它们解析为 int :) 看下面的代码

function multiply (val1, val2) {
val1 = parseInt(val1);
var n = val1;
for(var i = 1; i < val2; i++) {
n += val1;
}
return n;
}

var result = multiply(document.getElementById('first').value, document.getElementById('second').value);

document.getElementById('result').innerHTML = result;
<h1>Mutiplication Algorithm</h1>

<p>This algorithm attempts to multiply to given values without ever using the <span>*</span> operator</p>

<input id="first" type="text" value=5 /> x
<input type="text" id="second" value="4" /> =
<span id="result"></span>

关于javascript - 将输入值传递给 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43902814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com