【发布时间】: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)
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