gpt4 book ai didi

javascript - 如何为 DOM 创建的对象分配唯一标识符?

转载 作者:行者123 更新时间:2023-12-01 01:29:53 33 4
gpt4 key购买 nike

这是我的第一个问题,如果不够具体或缺少关键细节,我深表歉意。

我正在通过教程学习 JS,并将其应用于构建相当于套牌构建器的东西。

出现一堆卡片,您选择一张并将其添加到牌组中。这些卡牌将变成对象并添加到一个数组中,该数组代表选择放入牌组中的卡牌

当多张相同的卡片放入一副卡片中,并且您只想删除其中一张卡片时,就会出现问题。我不能只针对一张卡片,因为我的所有比较运算符都会选取这两个实例.

这是我在 Github 上的存储库,以防解释得不够清楚: https://github.com/caldwell619/armada-fleet/tree/data-attr

具体来说,以下是我正在努力解决的片段:

从数组中删除一艘船chosenFleet.ships:

for (var i = 0; i < chosenFleet.ships.length; i++) {
if ($(this).data("name") === chosenFleet.ships[i].name) {
chosenFleet.ships.splice(i, 1);

我尝试对所有对象应用唯一标识符,但由于我的函数基于重写 HTML,

 pickedShips.innerHTML = "";
for (let ship of chosenFleet.ships) {
// div creation
const shipSel = shipSelect(ship);
pickedShips.appendChild(shipSel);

所有唯一标识符最终都是相同的,因为每次事件监听器触发时,HTML 元素都会根据数组 ships 的当前状态进行重写。

根据选择的船舶创建 HTML 的函数:

const shipSelect = (ship) => {
const selectedShipContainer = document.createElement("div");
const shipImgContainer = document.createElement("div");
const shipNameContainer = document.createElement("div");
const shipImg = document.createElement("img");
const shipName = document.createElement("p");
const upgradeBar = document.createElement("div");
const deleteElement = document.createElement("span");
shipImgContainer.className = "span-4-of-12 ship-img";
shipImgContainer.appendChild(shipImg);
shipImg.src = "images/cards/ship/empire/" + ship.imageName;
selectedShipContainer.appendChild(shipImgContainer);
selectedShipContainer.className = "selected-ship-container";
upgradeBar.setAttribute("data-name", ship.name);
//add selected ship to new div
shipNameContainer.className = "span-7-of-12 ship-name";
shipNameContainer.appendChild(shipName);
shipNameContainer.appendChild(deleteElement);
deleteElement.className = "delete ion-trash-a";
deleteElement.setAttribute("data-name", ship.name);
deleteElement.setAttribute("data-points", ship.points);
//using data to make DOM manipulation
selectedShipContainer.setAttribute("data-name", ship.name);

shipName.innerHTML = ship.name;
selectedShipContainer.appendChild(shipNameContainer);
upgradeBar.className = "upgrade-bar";
selectedShipContainer.appendChild(upgradeBar);
const specificUpgrades = Object.keys(ship.upgrades);
for (let up of specificUpgrades) {
const butt = upgradeButtonMake(up);
upgradeBar.appendChild(butt);
}
pickedShips.appendChild(selectedShipContainer);
// return throwaway;
return selectedShipContainer;

};

再次,如果这太长/太短/等等,我深表歉意。菜鸟在这里。

最佳答案

您可以创建更具体的羊身份例如类似

deleteElement.setAttribute("data-id", ship.name + ship.type);

类型是能够更好地指定您的飞船的任何属性。

然后比较这个属性

if ($(this).data("id") === chosenFleet.ships[i].name + chosenFleet.ships[i].type) {

关于javascript - 如何为 DOM 创建的对象分配唯一标识符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53385204/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com