JavaScript动态生成图片点击提示逻辑异常问题排查求助
Hey there, let's get your image click alerts working correctly! The issue is pretty straightforward once you spot it—here's what's going wrong and how to fix it:
The Root Problem
In your click event listener, you're comparing the DOM image element (CardImage) directly to the string "A1" with this line:
if (CardImage === "A1") {
CardImage is an HTMLImageElement object, not a string. Comparing an object to a string will always be false, which is why every click triggers the "No" alert, even when you click the A1 image.
Solution 1: Use the Original Image Data
Since your DisplayImage function receives the index i of the image in your images$front array, you can directly reference the name property from that array entry in your condition:
function DisplayImage(i) { let CardImage = document.createElement('img'); CardImage.src = `Images/${images$front[i].img}` CardImage.alt = CardImage.src; document.querySelector("#box").appendChild(CardImage); CardImage.addEventListener("click", function(e) { // Compare the name from your image data instead of the DOM element if (images$front[i].name === "A1") { alert("Yes") } else { alert("No") } console.log(e.target.src) }) }
Solution 2: Add a Custom Data Attribute to the Image
Another robust approach is to attach the image's name directly to the DOM element using a data-* attribute. This makes the identifier accessible right on the element when the click happens:
function DisplayImage(i) { let CardImage = document.createElement('img'); CardImage.src = `Images/${images$front[i].img}` CardImage.alt = CardImage.src; // Store the image name in a custom data attribute CardImage.dataset.name = images$front[i].name; document.querySelector("#box").appendChild(CardImage); CardImage.addEventListener("click", function(e) { // Read the name from the data attribute on the clicked element if (e.target.dataset.name === "A1") { alert("Yes") } else { alert("No") } console.log(e.target.src) }) }
Either of these fixes will correctly check if the clicked image is "A1" and show the right alert. The second solution is especially useful if you ever need to access the image's name elsewhere in your code—since it's stored directly on the DOM element, you don't have to rely on the original array index.
内容的提问来源于stack exchange,提问作者user17191803

