html javascript(游戏)如何在点击按钮时获取按钮点的值



我正在创建一个游戏。游戏应该这样运行:当用户点击之前从下拉列表中选择的带有目标选项的按钮时,分数将为+2,否则为-1。

然而,我现在的代码不起作用,分数没有增加,总是0。我猜这是因为我没有正确检索按钮的值,因此,所选按钮的值和目标选项的值永远不匹配。我该如何解决这个问题

背景信息:根据所选的难度等级,这3个选项将每1/2/3秒刷新一次。因此,选项总是不同的,也会出现3个选项都不是目标选项的情况。用户可以选择等待1/2/3秒,或者点击任何选项并获得-1分。

这是我计算分数的部分的代码

document.getElementById("TO1").addEventListener("click", clickScore);
document.getElementById("TO2").addEventListener("click", clickScore);
document.getElementById("TO3").addEventListener("click", clickScore);

//score system
function clickScore() {
//when one option is clicked , all 3 options will change value
var option1 = document.getElementById("TO1").value;
var option2 = document.getElementById("TO2").value;
var option3 = document.getElementById("TO3").value;

var btn1 = document.getElementById("TO1");
var btn2 = document.getElementById("TO2");
var btn3 = document.getElementById("TO3");

if (btn1.clicked && option1.hasAttribute(targetValue) == true ){

score = parseInt(document.getElementById("score").innerHTML);

score += 2;
//random10Opt;

} 
else if (btn1.clicked && option1.hasAttribute(targetValue) == false)
{
score -=1;
//random10Opt;
}

if (btn2.clicked && option2.hasAttribute(targetValue) == true ){

score = parseInt(document.getElementById("score").innerHTML);

score += 2;
//random10Opt;

} 
else if (btn2.clicked && option2.hasAttribute(targetValue) == false)
{
score -= 1;
//random10Opt;
}    

if (btn3.clicked && option3.hasAttribute(targetValue) == true ){

score = parseInt(document.getElementById("score").innerHTML);

score += 2;
//random10Opt;

} else if (btn3.clicked && option3.hasAttribute(targetValue) == false)
{
score -= 1;
//random10Opt;
}

document.getElementById("score").innerHTML = score; 

}; //end of click

这是我有的全部代码

<!DOCTYPE html>
<html>
<body>
<div>

<form name="start" id="start">

<table id="T">
<tr id="Ttitle"> <!-- Header -->
<th colspan="3"><h2>Assignment 3 Part 2: Game</h2></th>
</tr>
<tr id="Tplayer"> <!-- ROW 1 PLAYER NAME-->
<th>Player Name</th>
<td><!-- text box for Unique name -->
<input type="text" id="name" name="required name" placeholder="Enter your Name"><br> 
<span style="color:red;" id="nameError"></span>
</td> 
<td id="TS" rowspan="3"> <!-- TIMER AND SCORE -->
<h3>Time: </h3>
<div class="timeScore" ><span id="seconds">00</span>:<span id="tens">00</span> second(s)</div>
<h3>Score: </h3>
<div class="timeScore" ><span id="score">0</span></div> 
</td> <!-- Time and Score -->
</tr>
<tr id="Ttarget"> <!-- ROW 2 TARGET OPTION-->
<th>The Target Option: </th>
<td> <!-- list box with all option -->
<select name="target_Opt" id="target_Opt">
<option value="">Choose your Target</option>                                
</select>
<span style="color:red;" id="TargetError"></span>
</td> 
</tr>
<tr id="Tdifficulty"> <!-- ROW 3 DIFFICULTY LEVEL-->
<th>The Difficulty Level: </th>
<td id="radio"> <!-- Radio button Low, Med, High -->

<input type="radio" id="Low" name="difficulty" value="low" checked>
Low

<input type="radio" id="Medium" name="difficulty" value="med">
Medium
<input type="radio" id="High" name="difficulty" value="high">
High

</td> 
</tr>
<tr id="Tbutton"> <!-- ROW 4 START STOP Button-->
<td colspan="3">
<input type="button" id="startBtn" 
value="Start" >

<input type="button" id="stopBtn"  value="Stop" >
</td>
</tr>
<tr id="Toptions"> <!-- ROW 5 CLICK Options -->
<td class="Opt">

<input type="button" class="gameOpt" id="TO1" value="Option 1" >
</td>
<td class="Opt">

<input type="button" class="gameOpt" id="TO2" value="Option 2" >
</td>
<td class="Opt">

<input type="button" class="gameOpt" id="TO3" value="Option 3" >
</td>
</tr>

</table>

<div id="Tlist" >
<h4> Player Listing : </h4>
<ul id="myList">
</ul>
</div>    
</form> <!--END OF FORM WHEN START IS CLICKED  --> 

</div>
</body>
<script> 
var score = 0; //for score

var pn = []; //Array to contain PlayerName
var ten = []; //Array for 10 Random Options

var a = document.forms["start"]["name"].value; //get Player's name input
var targetValue = document.getElementById("target_Opt").value; //selected target
//ARRAY OF OPTIONS TO CHOOSE TARGET
var Opt123 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var OptABC = ["A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "O", 
"P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z"];


//add options into dropdown list
function PrepopulateOpt() {

var selectTarget = document.getElementById("target_Opt");
var i = 1;
//add Opt123 into dropdown list
for (var target_Opt in Opt123) {
selectTarget.options[i++] = new Option(target_Opt);
}

//add OptABC into dropdown list
for (var i = 0; i < OptABC.length; i++) {
var opt = OptABC[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
selectTarget.appendChild(el);
}
}
PrepopulateOpt();

window.onload = function () {
var seconds = 00; 
var tens = 00 ; 
var appendTens = document.getElementById("tens");
var appendSeconds = document.getElementById("seconds");
var buttonStart = document.getElementById('startBtn');
var buttonStop = document.getElementById('stopBtn');
var Interval ;

var optionButton = document.getElementsByClassName('gameOpt'); //the options
//var changeOpt = document.getElementsByClassName("gameOpt").value; //option value

function ValidateEvent(){
var name = document.getElementById("name").value;
var target = document.getElementById("target_Opt").value;
//CHECK IF PLAYER NAME IS UNIQUE  
if (name == null || name.trim() == "")
{
alert("Please enter your name");
return false;

} else if (pn.includes(name) == true){
alert("Please enter a unique name");
return false;
} 
//CHECK IF TARGET IS SELECTED

if (target == "")
{
alert("Please select a target!") ;
return false;
}
else
{
document.getElementById("TargetError").value = "";
}  
return true;                   
}
/*        function removeDuplicates(data){
return data.filter((value, index) => data.indexOf(value) === index);
}

*/         
function random10Opt(){

//targetValue = selected target value;
var target = document.getElementById("target_Opt").value;
//var target123 = parseInt(document.getElementById("target_Opt").value);
var index;

const newArr = [];
if (Opt123.includes(target) == true){
index = Opt123.indexOf(target);
Opt123.splice(index, 1);
return Opt123;    

} else if (OptABC.includes(target) == true){

index = OptABC.indexOf(target);
OptABC.splice(index, 1);

return OptABC;
}
const a = Opt123.slice();
const b = OptABC.slice();

//select random 5 from digit add into newArr
for(let i= 5; i >= 0; i--){
let arr = a[Math.floor(Math.random()*a.length)];
let index = a.indexOf(arr);
a.splice(index, 1 );
newArr.push(arr);

}

for(let i= 5; i >= 0; i--){
let arr = b[Math.floor(Math.random()*b.length)];
let index = b.indexOf(arr);
b.splice(index, 1 );
newArr.push(arr);

}

newArr.push(target); //new array with randomized values : newArr


//enter random element into Option 1
var index1 = newArr[Math.floor(Math.random()*newArr.length)];
document.getElementById("TO1").value = index1;
var Arr2 = newArr.splice(index1, 1);

//enter random element into Option 2
var index2 = newArr[Math.floor(Math.random()*newArr.length)];
document.getElementById("TO2").value = index2;
var Arr3 = newArr.splice(index2, 1);

//enter random element into Option 3
var index3 = newArr[Math.floor(Math.random()*newArr.length)];
document.getElementById("TO3").value = index3;
console.log(newArr)
} //end of random10Opt

function difficultylvl() {
//TIME INTERVAL ACCORDING TO DIFFICULTY LEVEL
if (document.getElementById("Low").checked){
myVar =  setInterval(random10Opt, 3000);
} else if (document.getElementById("Medium").checked){
myVar = setInterval(random10Opt, 2000);
} else {
myVar =  setInterval(random10Opt, 1000);
} 

} //end of difficulty level

//stop timeInterval for difficulty level
function stopInterval() {
clearInterval(myVar);
}

document.getElementById("TO1").addEventListener("click", clickScore);
document.getElementById("TO2").addEventListener("click", clickScore);
document.getElementById("TO3").addEventListener("click", clickScore);

//score system
function clickScore() {
//when one option is clicked , all 3 options will change value
var option1 = document.getElementById("TO1").value;
var option2 = document.getElementById("TO2").value;
var option3 = document.getElementById("TO3").value;

var btn1 = document.getElementById("TO1");
var btn2 = document.getElementById("TO2");
var btn3 = document.getElementById("TO3");

if (btn1.clicked && option1.hasAttribute(targetValue) == true ){

score = parseInt(document.getElementById("score").innerHTML);

score += 2;
//random10Opt;

} 
else if (btn1.clicked && option1.hasAttribute(targetValue) == false)
{
score -=1;
//random10Opt;
}

if (btn2.clicked && option2.hasAttribute(targetValue) == true ){

score = parseInt(document.getElementById("score").innerHTML);

score += 2;
//random10Opt;

} 
else if (btn2.clicked && option2.hasAttribute(targetValue) == false)
{
score -= 1;
//random10Opt;
}    

if (btn3.clicked && option3.hasAttribute(targetValue) == true ){

score = parseInt(document.getElementById("score").innerHTML);

score += 2;
//random10Opt;

} else if (btn3.clicked && option3.hasAttribute(targetValue) == false)
{
score -= 1;
//random10Opt;
}

document.getElementById("score").innerHTML = score; 

}; //end of click

buttonStart.onclick = function() {
if( ValidateEvent() == true) {
//checkform();        //check name and target
random10Opt();      //add random value into button
difficultylvl();    //setInterval 
addName();          //add player name into list

if (seconds == 00 && tens == 00){
clearInterval(Interval);
Interval = setInterval(startTimer, 10);
} else {
clearInterval(Interval);
tens = "00";
seconds = "00";
appendTens.innerHTML = tens;
appendSeconds.innerHTML = seconds;
clearInterval(Interval);
Interval = setInterval(startTimer, 10); 
}        
}
};

buttonStop.onclick = function() {
clearInterval(Interval); //stop stopwatch
stopInterval();          //stop setInterval for options

//default value when the game stop
document.getElementById("TO1").value = "Option 1";
document.getElementById("TO2").value = "Option 2";
document.getElementById("TO3").value = "Option 3";


};

optionButton.onclick = function() {
clickScore(); //click the options for score
};


//stopwatch
function startTimer() {
tens++; 

if(tens < 9){
appendTens.innerHTML = "0" + tens;
}
if (tens > 9){
appendTens.innerHTML = tens;
} 
if (tens > 99) {
console.log("seconds");
seconds++;
appendSeconds.innerHTML = "0" + seconds;
tens = 0;
appendTens.innerHTML = "0" + 0;
}
if (seconds > 9){
appendSeconds.innerHTML = seconds;
}

}//end of startTimer()

function addName(){ 

//takes the value of player name             
//pn is an empty array to contain to names 
var newArray = document.getElementById("name").value;
pn.push(newArray);

var node = document.createElement("LI");
var textnode = document.createTextNode(newArray);

node.appendChild(textnode);
document.getElementById("myList").appendChild(node);  
} //end of addName function

};//end on onload

</script>
</html>

您已经注册了两次点击事件。刚刚删除了输入中的onclick

...
<input type="button" class="gameOpt" id="TO1" value="Option 1">
...
<input type="button" class="gameOpt" id="TO2" value="Option 2">
...
<input type="button" class="gameOpt" id="TO3" value="Option 3">
</td>
...
<script>
document.getElementById("TO1").addEventListener("click", clickScore);
document.getElementById("TO2").addEventListener("click", clickScore);
document.getElementById("TO3").addEventListener("click", clickScore);

看看下面的片段,我认为它说明了您试图实现的目标。

您的按钮将在开始时随机化。然后您可以选择";目标值";从下拉列表中,并单击按钮w/与您选择的"相匹配的值;目标值";将增加分数,而单击与目标值不匹配的按钮将减少分数。

请注意,以允许读取事件目标值的方式附加单击事件处理程序会变得多么简单。

var score = 0;
var newArr = [1, 2, 3, 4, 5, "A", "B", "C", "D", "E"];
let scoreOutput = document.getElementById("scoreUpdate");
const gameButtons = document.querySelectorAll(".gameOpt");
//this code just creates the select dropdown, which you don't need to do
var select = document.getElementById("targetValue");
for (var i = 0; i < newArr.length; i++) {
var opt = newArr[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
randomizeButtonValues();
//attach the click for each button
[...gameButtons].forEach((btn) => {
btn.addEventListener("click", (e) => {
let correctValue = document.getElementById("targetValue").value;
let clickedValue = e.target.value;  // <-- capture value of clicked element
console.log(correctValue, clickedValue);
if(correctValue == clickedValue) {
score += 2;
} else {
score -= 1;
}
scoreOutput.innerHTML += `<br>New Score: ${score}`;
randomizeButtonValues();
});
});
function randomizeButtonValues() {
[...gameButtons].forEach((btn) => {
let rnd = Math.floor(Math.random() * newArr.length);
btn.value = newArr[rnd];
});
}
<select id="targetValue">
<option>Choose target value</option>
</select>
<input type="button" class="gameOpt" id="TO1" value="Option 1">
<input type="button" class="gameOpt" id="TO2" value="Option 2">
<input type="button" class="gameOpt" id="TO3" value="Option 3">
<br>
<div id="scoreUpdate"></div>

最新更新