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

点击图片时获取到Undefined值的原因分析与解决方案

Why this.value returns undefined for your image element & how to fix it

Let's break down what's happening here and how to fix it quickly:

The Root Cause

The <img> element doesn't have a native value attribute in HTML. Even though you added value="01" to your img tag, browsers don't recognize this as a standard property for image elements. That's why when you try to access this.value in your onclick handler, it returns undefined. Native value attributes are only reserved for form elements like <input>, <select>, and <textarea>—images don't fall into that category.

HTML5 introduced data-* attributes specifically for storing custom data on any element. This is the cleanest, most standards-compliant way to handle this scenario.

Update your HTML to use data-value instead of value:

<div id="fi" value="0"> 
  <img src="first.JPG" alt="first" id="first" data-value="01" onclick="checkingg(this.dataset.value)"/> 
</div>

Your existing JavaScript function will work perfectly with this change:

function checkingg(img_val) {
  console.log(img_val); // Now logs "01" as expected
}

Alternatively, you can pass the entire element to the function and read the dataset inside it (this is more flexible if you need other data later):

<img src="first.JPG" alt="first" id="first" data-value="01" onclick="checkingg(this)"/>
function checkingg(imgElement) {
  console.log(imgElement.dataset.value); // Still logs "01"
}

Fix 2: Use getAttribute() for Custom Attributes

If you prefer to keep your original value attribute (though this isn't the recommended approach), you can use the getAttribute() method to directly fetch the custom attribute's value:

Keep your HTML as-is, but modify the onclick handler:

<div id="fi" value="0"> 
  <img src="first.JPG" alt="first" id="first" value="01" onclick="checkingg(this.getAttribute('value'))"/> 
</div>

Again, your existing JavaScript function will work without changes—it'll receive the "01" value correctly.

Quick Note on Best Practices

While getAttribute() works, sticking with data-* attributes is better long-term. They're purpose-built for custom data, avoid conflicts with future native HTML attributes, and make your code more readable for other developers who'll immediately recognize what the attribute is used for.

内容的提问来源于stack exchange,提问作者Siddharthsonii

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 09:47:39