我正在尝试用jQuery构建内存游戏,但是我在隐藏元素方面苦苦挣扎 那是我的html正文:
<body>
<div id="wrapper">
<input type="radio" name="size" id="4x4" value="16">
<label for="4x4">4x4</label>
<input type="radio" name="size" id="4x6" value="24">
<label for="4x6">4x6</label>
<input type="radio" name="size" id="6x6" value="36">
<label for="6x6">6x6</label>
<input type="button" value="Start" id="start">
<div id="memoryField">
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.0.min.js"
integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ="
crossorigin="anonymous"></script>
<script type="text/javascript" src="script.js"></script>
</body>
图片工作正常。问题是我一次只能看到两张图片,当我单击第三张图片时,最后两张图片应该再次不可见。
我尝试了一段时间,但是没有按照我想要的方式工作。 第二个问题是,我想隐藏带有图像的div,这也不起作用。
那是我的js代码:
let cards = $("input:radio[name = 'size']:checked").val();
let amountClicked = 0;
let clicks = 0;
$("#memoryField div").each(function () {
$(this).click(function () {
if ($("img", this).hasClass("hidden")) {
$("img", this).removeClass("hidden");
$("img", this).addClass("visible");
amountClicked++;
clicks++;
if (amountClicked == 2) {
if (($("img", last).attr("src") != $("img", this).attr("src")) && $("img", last).hasClass("visible")) {
let that = $(this);
window.setTimeout(function (that) {
$("img", last).removeClass("visible");
$("img", last).addClass("hidden");
$("img", that).removeClass("visible");
$("img", that).addClass("hidden");
amountClicked = 0;
}, 800);
} else {
let that = $(this);
window.setTimeout(function (that) {
$("img", that).parent().hide();
$("img", last).parent().hide();
amountClicked = 0;
cards -= 2;
}, 500);
}
}
}
last = $(this);
});
});
答案 0 :(得分:0)
好的,请注意,但首先,您不需要使用$(“#memoryField div”)。each(function(),只需使用$(“#memoryField div”)。click(function)将做 我无法测试您的代码,因为单击“开始”按钮后没有js, 但是,如果我正在执行此任务,我将使一切变得非常简单,像这样:
let amountClicked = 0;
$("#memoryField div").click(function() {
if ($("img", this).hasClass("hidden")) {
if (amountClicked == 2) {
$("#memoryField div img").removeClass("visible"); // Remove other img visible class
$("#memoryField div img").addClass("hidden");
amountClicked = 0; // Reset
}
$("img", this).removeClass("hidden");
$("img", this).addClass("visible");
amountClicked++;
}
});
应该可以