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

时间:2018-11-20 02:05:21

标签: javascript arrays loops object for-loop

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

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

};

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

2 个答案:

答案 0 :(得分:2)

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

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

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

然后比较这个属性

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

答案 1 :(得分:0)

创建一个像这样的全局对象

(function (global) {
  global.getUniq = getUniq;
  var id = 0;

  function getUniq() {
    return ++id;
  }
})(window);

这是一个单例,每次调用getUniq时,无论有多少客户端使用它,都会获得一个唯一的标识符。