【问题标题】:Getting error while trying to get title from structure尝试从结构中获取标题时出错
【发布时间】:2021-11-22 16:26:46
【问题描述】:

我需要帮助,我在尝试从结构中获取标题时遇到此错误,我不知道如何解决。

这段代码运行良好。


    function addCard(x,who) {
    
      if(who === 'player'){
        const  element = document.querySelector(".playercards");
        element.insertAdjacentHTML('afterbegin', `<button id='${x}' class='cardbutton'><p>${deck[x].title}</br></br>Action: ${deck[x].points} ${deck[x].action}</p></button>`);
      }
      if(who === 'bot'){
        const  element = document.querySelector(".botcards");
        element.insertAdjacentHTML('afterbegin', `<button id='bot${x}' class='cardbutton'><p>${deck[x].title}</br></br>Action: ${deck[x].points} ${deck[x].action}</p></button>`);
      }
    }
    
    playerCards.forEach((node, position) => addCard(node.getValue(),'player'));
    botCards.forEach((node, position) => addCard(node.getValue(),'bot'));

但是当我使用此代码时会发生此错误deck[cardId].title 它不起作用,我不知道为什么,我试图输入这样的数字deck[1].title,但它仍然给我一个错误。可能是什么问题?

Uncaught TypeError: Cannot read properties of undefined (reading 'title')
    at HTMLUListElement.clickedOnCard (gamescript.js:47)

Error image

47 行是


    console.log(deck[cardId].title())


    const deck = [
      {id: 0, title: 'Šokoladas', action: 'heal', points: 5},
      {id: 1, title: 'Sausainis', action: 'heal', points: 2},
      {id: 2, title: 'Pulti', action: 'damage', points: 3},
      {id: 3, title: 'Saukstas', action: 'damage', points: 1}
    ]

    document.querySelector(".playercards").addEventListener("click",clickedOnCard, false);
    
    function clickedOnCard(e) {
      if(e.target !== e.currentTarget){
        var cardId = e.target.id || e.srcElement.id;
        
        console.log(deck[cardId].title)
    
    
        // Deletes clicked player card
        removeCard(cardId);
    
        // Removes bot card
        removeCard(`bot${botCards.tail().getValue()}`);
        botCards.removeLast();
    
        updateHp();
    
        e.stopPropagation();
    
        postlog(getDate() + " Game: Button clicked." + " Used: " + cardId);
      }
    };

【问题讨论】:

    标签: javascript html data-structures


    【解决方案1】:

    你需要迭代你的数组来获取你的项目,请使用 find

    【讨论】:

    • 我只是想从html元素(按钮)document.querySelector(".playercards").addEventListener("click",clickedOnCard, false);中获取id
    • codeSandbox会更有帮助,好像不太清楚
    • 这是我的全部代码,我不知道如何使用codeSandbox,对不起codesandbox.io/s/youthful-darkness-dcvok?file=/gamescript.js
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    • 2020-06-05
    • 2016-05-26
    • 2020-07-25
    相关资源
    最近更新 更多