当我点击播放器1按钮时,两个玩家的分数都会改变。
我也尝试用echo WC()->cart->get_cart_contents_count();
选择p2display
似乎它将其称为querySelector("#p2Display")
而不是nodeList
。
element
var p1button = document.querySelector("#p1");
var p2button = document.getElementById("p2");
var p1Display = document.getElementById("p1Display");
var p2Display = document.getElementById("p2Display");
var p1Score = 0;
var p2Score = 0;
p1button.addEventListener("click", function() {
p1Score++;
p1Display.textContent = p1Score;
});
p1button.addEventListener("click", function() {
p2Score++;
p2Display.textContent = p2Score;
});
我的Codepen
答案 0 :(得分:2)
第二个事件应该附加到第二个按钮,而不是像:
p2button.addEventListener("click", function(){
^^^^^^^^
p2Score++ ;
p2Display.textContent = p2Score;
});
var p1button = document.querySelector("#p1");
var p2button = document.getElementById("p2");
var p1Display = document.getElementById("p1Display");
var p2Display = document.getElementById("p2Display");
var p1Score = 0;
var p2Score = 0;
p1button.addEventListener("click", function(){
p1Score++ ;
p1Display.textContent = p1Score;
});
p2button.addEventListener("click", function(){
p2Score++ ;
p2Display.textContent = p2Score;
});

<h1><span id="p1Display">0</span> To <span id="p2Display">0</span></h1>
<p>Playing to: 5</p>
<input type="number">
<button id="p1">Player One</button>
<button id="p2">Player Two</button>
<button id="reset">Reset </button>
&#13;
答案 1 :(得分:1)
添加事件侦听器是一个小的复制粘贴错误。 querySelector也适用于这两个元素。检查下面的代码。
var p1button = document.querySelector("#p1");
var p2button = document.querySelector("#p2");
var p1Display = document.getElementById("p1Display");
var p2Display = document.getElementById("p2Display");
var p1Score = 0;
var p2Score = 0;
/*
//p1 btn
for(var i = 0; i < p1button.length; i++){
p1button[i].addEventListener("click", function(){
alert("clicked") });
};
*/
p1button.addEventListener("click", function(){
p1Score++ ;
p1Display.textContent = p1Score;
});
p2button.addEventListener("click", function(){
p2Score++ ;
p2Display.textContent = p2Score;
});
&#13;
<h1><span id="p1Display">0</span> To <span id="p2Display">0</span></h1>
<p>Playing to: 5</p>
<input type="number">
<button id="p1">Player One</button>
<button id="p2">Player Two</button>
<button id="reset">Reset </button>
&#13;