javascript onChange事件监听器不适用于输入表单

时间:2015-03-15 20:18:59

标签: javascript html onchange event-listener

当我按下这个按钮时:

<div id="Input #1">
<label for="input1">Input #1:</label>
<input type="number" id="input1" name="input1" onchange="i1set()">
</div>

然后有这个JavaScript:

var i1 = undefined;
var i1set = function(){
  i1 = document.getElementById("input1").value;
}
var solution = parseFloat(i1)+parseFloat(i2);
    alert(solution);

没问题。

但是,当我消除html的onchange部分,而不是在js中创建一个事件监听器时,我就会遇到问题。其中一个问题是让parseFloats给我“NaN”而不是一个数字答案......但更大的问题是,即使我摆脱了parseFloats,即使有减法,加法,除法,它也给了我奇怪的错误答案。

以下是我目前不再有效的代码:

<form>
 <input type="radio" id="addition" name="addition" value="addition"><label>Addition</label><br>
 <input type="radio" id="subtraction" name="subtraction" value="subtraction"><label>Subtraction</label><br>
 <input type="radio" id="multiplication" name="multiplication" value="multiplication"><label>Multiplication</label><br>
 <input type="radio" id="division" name="division" value="division"><label>Division</label><br>

 <div id="Input #1">
  <label for="input1">Input #1:</label>
  <input type="number" id="input1" name="input1">
 </div>
 <div id="Input #2">
  <label for="input2">Input #2:</label>
  <input type="number" id="input2" name="input2">
 </div>
 <input type="submit" id="submit" value="Solve" />
</form>

<script>
var i1 = undefined;
var i2 = undefined;
var i1set = function(){
i1 = document.getElementById("input1").value;
}
var i2set = function(){
i2 = document.getElementById("input2").value;
}
var solve = function(){
    if ( (i1 != undefined) && (i2 != undefined) ) {
        if(document.getElementById('addition').checked) {
    var solution = parseFloat(i1)+parseFloat(i2);
    alert(solution);
    }
    if(document.getElementById('subtraction').checked) {
    var solution = i1-i2;
    alert(solution);
    }
    if(document.getElementById('multiplication').checked) {
    var solution = i1*i2;
    alert(solution);
    }
    if(document.getElementById('division').checked) {
    var solution = i1/i2;
    alert(solution);
    }
    }
}
document.getElementById("input1").addEventListener("change", i1set(), false);
document.getElementById("input2").addEventListener("change", i2set(), false);
document.getElementById("submit").addEventListener("click", solve, false);

</script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

问题是空字符串不等于udnefined所以检查:

if ((i1 != undefined) && (i2 != undefined)) {

表现得不像你期望的那样。 if块可以更简单:

if (i1 && i2) { // or i1 !== '' && i2 !== ''

第二个问题是你需要提供函数引用作为事件监听器,而不是使用()立即执行它:

document.getElementById("input1").addEventListener("change", i1set, false);
//                             Note, you don't need () here ------^