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

JavaScript中option.dataset命名异常:为何出现data-data-unitprice?

问题描述

我正在通过<select>和<input>组件添加新行,当<option>的dataset存在值时更新<input>。以下是相关代码:

var optionsArray = [
    { value: "", text: "Pick" },
    { value: "1", text: "Option 1", dataUnitprice: "100" },
    { value: "2", text: "Option 2", dataUnitprice: "200" },
    { value: "3", text: "Option 3", dataUnitprice: "" },
];
optionsArray.forEach(function (optionData) {
    var option = document.createElement("option");
    option.value = optionData.value;
    option.textContent = optionData.text;
    option.dataset.dataEnhedspris = optionData.dataUnitprice;
    selectClone.appendChild(option);
});
var selectClone = document.createElement("select");
selectClone.className = "select-option form-control form-control-sm";
selectClone.setAttribute("data-show-content", "true");
selectClone.name = "kategori";
selectClone.required = true;
selectClone.onchange = function () {
    updateUnitprice(this);
};

但运行后控制台显示<option value="1" data-data-unitprice="">Option 1</option>,出现了未定义的data-data-unitprice,而非预期的dataUnitprice,请问这是什么原因?是否需要在代码中使用连字符?


原因与解决方案

这是因为DOM的dataset API遵循驼峰转短横线的命名规则:

  • 当通过element.dataset设置属性时,驼峰命名的属性名会被自动转换为短横线分隔的data-*属性。
  • 你代码中写的option.dataset.dataEnhedspris,会被解析成data-data-enhedspris(也就是你看到的data-data-unitprice,属于变量名翻译差异),完全不符合预期。

正确的处理方式有两种:

  1. 使用dataset的驼峰命名:若要在HTML中得到data-unitprice属性,在dataset里对应使用驼峰名unitprice
  2. 直接调用setAttribute方法:直接设置原生的data-*属性,无需遵循dataset的命名转换规则

修改后的创建option代码示例:

optionsArray.forEach(function (optionData) {
    var option = document.createElement("option");
    option.value = optionData.value;
    option.textContent = optionData.text;
    // 方式1:dataset驼峰命名
    option.dataset.unitprice = optionData.dataUnitprice;
    // 方式2:直接设置原生data属性
    // option.setAttribute('data-unitprice', optionData.dataUnitprice);
    selectClone.appendChild(option);
});

修改后,HTML中会生成符合预期的<option value="1" data-unitprice="100">Option 1</option>。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 18:52:57