You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript动态生成图片点击提示逻辑异常问题排查求助

Fixing the Click Alert Logic for Dynamically Generated Images

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 19:42:35