0

我只想随机点击某个按钮,然后当我点击 Sum 按钮时,它会显示点击按钮值结果的总和,我需要这个带有 java 脚本的代码。

<!DOCTYPE html>
<html>
<head>
<script>
var mynum = new Array(6);
var i = 0;

unction buttonClicked(obj) {
if (i < mynum.length) 
 mynum[i++] = obj.value; 
else alert("Array limit reached");
}

function sum() {
sumOfArray = 0;
for (j = 0; j < i; j++)
sumOfArray += parseInt(mynum[j++]);
alert("Sum = " + sumOfArray);
}

</script>
</head>
<body>


<p id="demo">Result</p>


button type="button" onclick="buttonClicked(2)">1</button>

<button type="button" onclick="buttonClicked(3)">2</button>
<button type="button" onclick="buttonClicked(3)">4</button>
<button type="button" onclick="buttonClicked(3)">8</button>


<button type="button" onclick="sum()">Sum</button>

</body>
</html> 
4

1 回答 1

2

This line:

unction buttonClicked(obj) {

should be:

function buttonClicked(obj) {

As you are sending the value to the function, and not an object containing the value, this:

mynum[i++] = obj.value;

should be:

mynum[i++] = obj;

As you have numbers in the array, you shouldn't parse them. This:

sumOfArray += parseInt(mynum[j++]);

should be:

sumOfArray += mynum[j++];

Side note: When you do use parseInt you should specify the base as the second parameter, otherwise it will parse numbers that start with a zero using base 8 instead of 10.


You probably want to send a value to the function that corresponds to what the button shows, so this:

button type="button" onclick="buttonClicked(2)">1</button>
<button type="button" onclick="buttonClicked(3)">2</button>
<button type="button" onclick="buttonClicked(3)">4</button>
<button type="button" onclick="buttonClicked(3)">8</button>

should be:

<button onclick="buttonClicked(1)">1</button>
<button onclick="buttonClicked(2)">2</button>
<button onclick="buttonClicked(4)">4</button>
<button onclick="buttonClicked(8)">8</button>
于 2013-06-03T11:22:02.367 回答