HTML代码
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="score-board.css">
<title>Score Board App</title>
</head>
<body>
<div id="playersscores">
<span id="p1score">0</span><span> To </span> <span id="p2score">0</span>
</div>
<p>Playing to <span id="score">5</span></p>
<input type="field" value="5" ></input>
<button id="p1clicked">Player one</button>
<button id="p2clicked">Player two</button>
<button id="reset">Reset</button>
<script type="text/javascript" src="score-board.js"></script>
</body>
</html>
Javascript是:
每当加载此代码时:
var p1result = document.querySelector("#p1score");
var p2result = document.querySelector("#p2score");
var p1clicked = document.querySelector("#p1clicked");
function increment_score (player_result) {
//var score = parseInt(player_result.innerText) + 1;
player_result.innerText = (parseInt(player_result.innerText) + 1).toString();
}
p1clicked.addEventListener("onclick", increment_score(p1result))
每当在浏览器中加载此代码时,显示播放器1结果的范围直接显示一个,而不单击播放器1按钮。我不确定使用的事件监听器有什么问题。
答案 0 :(得分:1)
该活动为click
,而非onclick
事件监听器应该是对函数本身的引用,而不是函数调用的结果(将分数增加1)
在功能内部,您可以使用this
访问该按钮:
代码可能如下所示:
function increment_score() {
var player_result = this;
player_result.innerText = (parseInt(player_result.innerText) + 1).toString();
}
p1clicked.addEventListener('click', increment_score);
答案 1 :(得分:1)
click
事件而不是onclick
p1clicked.addEventListener("click", increment_score.bind({result: p1result, inc: 1 }) )
p2clicked.addEventListener("click", increment_score.bind({result: p2result, inc: 2 }) )
function increment_score () {
var score = parseInt(this.result.innerText) + this.inc;
this.result.innerText = score;
}
答案 2 :(得分:1)
那里有几个问题。首先,在调用addEventListener函数时,您只需指定“click”,而不是“onclick”。其次,当您将函数传递给addEventListener时,您只希望它是对函数的引用而不是实际的函数调用。以下更改将为您提供所需的结果。
function increment_score () {
p1result.innerText = (parseInt(p1result.innerText) + 1).toString();
}
p1clicked.addEventListener("click", increment_score);
但是既然你想能够为多个玩家使用相同的功能,那么我建议在HTML中添加“onclick”处理程序,这将允许你传递你想要增加的元素。那么您的HTML代码将如下所示:
<button id="p1clicked" onclick="increment_score_with_param(p1result);">Player one</button>
<button id="p2clicked" onclick="increment_score_with_param(p2result);">Player two</button>
,你的javascript就是:
var p1result = document.querySelector("#p1score");
var p2result = document.querySelector("#p2score");
var p1clicked = document.querySelector("#p1clicked");
function increment_score_with_param (player_result) {
player_result.innerText = (parseInt(player_result.innerText) + 1).toString();
}
答案 3 :(得分:0)
window.onload = function(){
var p1result = document.querySelector('#p1score');
var p2result = document.querySelector('#p2score');
var p1clicked = document.querySelector('#p1clicked');
p1clicked.addEventListener("click", function(e){
e.preventDefault();
p1result.innerText = (parseInt(p1result.innerText) + 1).toString();
});
}
&#13;