JavaScript:点击动态生成塔罗牌图片无法获取.data数据求助
Hey there! Let's figure out why your click handler is logging undefined instead of the pre-stored tarot card data. This is a super common pitfall with dynamic DOM elements and event handlers—here are the most likely fixes based on typical code patterns for this kind of game:
Common Cause 1: Closure Trap in Loops
If you're generating cards inside a loop (which I bet you are!), using var for your loop variable (instead of let/const) can break data capture. Here's what that broken code might look like:
let ajouterImageCarte = function() { var cartes = [/* your tarot card data array */]; for(var i = 0; i < cartes.length; i++) { let img = document.createElement('img'); img.src = cartes[i].src; img.onclick = function() { console.log(cartes[i]); // Logs undefined! } document.body.appendChild(img); } }
Why this breaks:
var has function-level scope, so by the time you click the card, the loop has finished and i equals cartes.length—so cartes[i] doesn't exist.
Fix:
Use let for the loop variable (it has block-level scope, so each iteration gets its own i), or better yet, use forEach to iterate over your cards:
let ajouterImageCarte = function() { const cartes = [/* your tarot card data array */]; cartes.forEach(carte => { const img = document.createElement('img'); img.src = carte.src; // The `carte` variable is captured correctly here img.addEventListener('click', () => { console.log(carte); // Logs the correct card data! }); document.getElementById('card-container').appendChild(img); }); }
Common Cause 2: Incorrect Data Storage on the Image Element
If you're storing data directly as a custom property on the img element (like img.myData = carte), it might not persist or be accessible in the click handler. DOM elements work best with the dataset API for custom data.
Broken Example:
img.myCardData = carte; img.onclick = function() { console.log(this.myCardData); // Undefined! }
Fix: Use dataset (with JSON for complex objects)
Since dataset only stores strings, stringify complex objects and parse them back in the handler:
let ajouterImageCarte = function() { const cartes = [/* your tarot card data array */]; cartes.forEach(carte => { const img = document.createElement('img'); img.src = carte.src; // Store simple values directly img.dataset.cardId = carte.id; img.dataset.cardName = carte.name; // Stringify complex objects img.dataset.cardDetails = JSON.stringify(carte.details); img.addEventListener('click', function() { // Retrieve and parse the data const cardData = { id: this.dataset.cardId, name: this.dataset.cardName, details: JSON.parse(this.dataset.cardDetails) }; console.log(cardData); // Correct data! }); document.getElementById('card-container').appendChild(img); }); }
Quick Checks to Verify
- Right-click a card in your browser, select "Inspect", and check the
datasetsection in the Elements tab—make sure your data is actually being stored there. - Ensure you're not overwriting the
onclickhandler later in your code (usingaddEventListenerinstead ofonclickavoids this issue).
内容的提问来源于stack exchange,提问作者Vincent Mazel

