初学者使用javascript,遇到表单问题,用户输入5个整数然后进入数组然后计算总和 使用google web dev工具获取事件监听器的错误。我离开了吗?
HTML
<article>
<h2> Enter five intergers then click add to calculate the sum </h2>
<h5>please do not include any letters</h5><br>
<br>Enter the 1st number: <input type="text" id="txt1" /><br>
<br>Enter the 2nd number: <input type="text" id="txt2" /><br>
<br>Enter the 3rd number: <input type="text" id="txt3" /><br>
<br>Enter the 4th number: <input type="text" id="txt4" /><br>
<br>Enter the 5th number: <input type="text" id="txt5" /><br>
<br><input type="button" onclick="call()" value="Add" id="sum" />
<br>
</article>
JAVASCRIPT
function add () {
var txt1 = document.getElementById("txt1");
var txt2 = document.getElementById("txt2");
var txt3 = document.getElementById("txt3");
var txt4 = document.getElementById("txt4");
var txt5 = document.getElementById("txt5");
var arr = [txt1,txt2,txt3,txt4,txt5];
var total=0;
for(var i in arr) { total += arr[i]; }
if(isNaN(txt1)||isNaN(txt2)||isNaN(txt3)||isNaN(txt4)||isNaN(txt5)){
alert("please enter a number");
}
else
{
var result=txt1+txt2+txt3+txt4+txt5;
alert("The sum is " +result);
}
}
// listener
function createEventListener() {
var submitButton = document.getElementById("sum");
if (submitButton.addEventListener) {
submitButton.addEventListener("click", add, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", add);
}
document.getElementById('result').result = "";
document.getElementById('sum').innerHTML = "";
}
if (window.addEventListener) {
window.addEventListener("load", createEventListener, false);
} else if (window.attachEvent) {
window.attachEvent("onload", createEventListener);
}
答案 0 :(得分:0)
您的onclick正在调用您尚未定义的call()。我认为你的意思是add()
答案 1 :(得分:0)
首先,它应该是add
,而不是call
:
<input type="button" onclick="add()" value="Add" id="sum" />
然后必须改变这些:
var txt1 = Number(document.getElementById("txt1").value);