致意,
我正在通过一些在线资源和我在该领域工作的兄弟学习编码,以努力进入开发职业。现在我正在开发一个愚蠢的网络应用程序,您可以在其中匹配照片。每张照片下方都有一个带有唯一 ID 的按钮。目前,当您选择一个按钮时,它会变成蓝色。
我正在尝试创建一个函数,该函数将查找 2 个被点击的特定按钮。
如果我要在与您的对话中说出我想让它做什么,我会说“如果在选择 button4 时选择了 button1,请执行此操作”
我在寻找什么功能?
谁能帮帮这个 n00b 吗?
下面我有点击按钮时的功能。类发生变化以调整颜色。
我可以发布任何必要的代码,否则我只能发布这些。 {BC1b 是一个应该与 F1b 配对的按钮}
function sbtnb1() {
document.getElementById("BC1b").className = "selected";
}
最佳答案
这是一个例子。
https://jsfiddle.net/273rhzyw/
使用 Jquery https://jsfiddle.net/agoLcuv8/8/
// All buttons with class of button
const buttons = document.querySelectorAll(".button");
// declare array to keep the match checks
let matchCheckerArray = [];
// Loop through each button and attach an onClick
buttons.forEach(function(button) {
button.onclick = function() {
clickHandler(button);
}
});
const clickHandler = function(button) {
matchCheckerArray.push(button.dataset.matchId)
console.log(matchCheckerArray);
if (matchCheckerArray.length == 2) {
if (isMatch()) {
alert('Match');
}
matchCheckerArray = [];
return;
}
}
const isMatch = function() {
if (matchCheckerArray[0] === matchCheckerArray[1]) {
return true;
}
return false;
}
关于javascript - 我如何构建一个函数来查找 2 个被单击的特定按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58848351/