javascript - 单击正确的图像时如何增加计数器
问题描述
我用 HTML 和 Javascript 编写了一个网页,该网页在狮子和青蛙的图像中循环。我设置了 2 个按钮来启动和停止图像每 500 毫秒循环一次。我的问题是我不确定如何创建一个分数函数来计算特定图像被点击的次数。例如,如果点击青蛙图像,我希望得分为 +1,如果点击狮子图像,我希望得分为 -1。这是我的代码。
<html>
<head>
<title>Question 2</title>
<script>
var images = ["frog.jpg", "lion.jpg"] //I Created an array with both images inside
var imgInterval;
var imgi = 'empty';
var score = document.getElementById('score');
function start(){
imgInterval = setInterval(displayImage, 500); //Sets an interval for the func displayImage and for it to loop ever 500ms
}
function displayImage() {
if (imgi == 'empty') { //If the index is empty set the interval to 0 or frog.jpg
imgi = 0;
} else if (imgi == 0) { // If the index is set to 0 set it to 1 or lion.jpg
imgi = 1;
} else if (imgi == 1) { // If the idex is set to 1 set it back to 0, this creates a loop that will be run every 500ms
imgi = 0;
}
document.getElementById('image').src = images[imgi];
}
function stop(){
clearInterval(imgInterval);
}
function scoreNumb() { //This is where i think i am having issues and am unsure what to do.
if (imgi.onclick == 0) {
score + 1;
}
}
</script>
</head>
<body>
<button onclick=start()>Start Animation</button>
<button onclick=stop()>Stop Animation</button>
<br/> <br/>
<span>
<img id="image" onclick=scoreNumb() width="250px" />
</span>
<br/>
<span id="score">0</span>
</body>
</html>
解决方案
用我的替换你的函数 scoreNumb
<script>
...
var score = document.getElementById('score');
var valueScore = 0; /*created this*/
...
function scoreNumb() { //This is where i think i am having issues and am unsure what to do.
/*if (imgi.onclick == 0) {
score + 1;
}*/
/*0 = frog AND 1 = lion*/
if (imgi == 0){/*+1*/
valueScore++;
}else {
valueScore--;
}
console.log("click", valueScore);
document.getElementById('score').textContent = valueScore;
}
推荐阅读
- performance - Chrome + 开发工具性能不佳
- google-workspace - 无法从谷歌工作区市场找到 Colaboratory
- python - python、bs4、.csv——为什么我的函数不能正确重复?
- react-native - React native android scrollview - 未应用内容插入/内容偏移
- typescript - cy.intercept() 不在赛普拉斯中存根 API
- r - lm_model 添加的意外符号错误
- powershell - 将 PowerShell cmdlet 的错误级别传递给批处理文件
- javascript - 似乎无法在 three.js 中向场景添加文本
- python - 来自数据框的 Python networkx 绘图,线宽取决于列值
- stackexchange.redis - 无法使用 SSL 连接到 Azure Cache for Redis