首页 > 解决方案 > 如何为 DOM 创建的对象分配唯一标识符?

问题描述

这是我的第一个问题,如果不够具体或缺少关键细节,敬请见谅。

我正在通过教程学习 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;

};

同样,如果这太长/太短/等等,我很抱歉。菜鸟在这里。

标签: javascriptarraysloopsobjectfor-loop

解决方案


您可以创建更具体的绵羊身份,例如

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

type是可以更好地指定您的船的任何属性。

然后在这个属性上进行比较

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

推荐阅读