添加点击事件处理程序
在这一步中,你将为页面顶部的水果物品添加点击事件处理程序。
- 在
index.html
文件中,找到 <script>
标签内的 TODO 部分。
<script>
标签内部设置了一个空的 ids
变量数组。
let ids = [];
$("#card li").on("click", function (e) {
// TODO: 请在此处实现该函数
});
- 在 TODO 部分添加以下代码:
$("#card li").on("click", function (e) {
// TODO: 请在此处实现该函数
if ($("#box li").length >= 7) {
return;
}
let clone = $(this).clone();
$("#box").append(clone);
let currentId = $(this).data("id");
ids.push($(this).data("id"));
let currentIdLen = ids.filter((id) => id == currentId)?.length;
if (currentIdLen == 3) {
ids = ids.filter((id) => id !== currentId);
let three = $(`#box li[data-id=${currentId}]`);
for (let index = 0; index < three.length; index++) {
const element = three[index];
$(element).addClass("active");
setTimeout(() => {
element.remove();
}, 200);
}
}
$(this).css({
top: "600px",
left: "200px",
opacity: 0,
transition:
"left.2s linear, top.2s cubic-bezier(.08,-0.35,.99,.33),opacity.2s linear"
});
});
这段代码为页面顶部的水果物品添加了一个点击事件处理程序。当点击一个水果物品时,它将被克隆并添加到页面底部的盒子中。如果盒子里有三个相同的水果,它们将被移除。如果底部矩形(id=box
)元素中有7个水果且无法消除,则点击的水果元素节点不在添加的矩形元素中。