我正在动态创建元素,这是我用于一个单元格的代码。
我想添加一个带有自定义值的数据属性。
我试过了:
elCostPrice.data-num = i;
elCostPrice.data["num"] = i;
elCostPrice.prop["num", i]
Run Code Online (Sandbox Code Playgroud)
但这些都没有用
var Cell3 = row.insertCell(3);
var elCostPrice = document.createElement('input');
elCostPrice.type = 'text';
elCostPrice.className = 'cost_price form-control required';
elCostPrice.name = 'cost_price' + i;
elCostPrice.id = 'cost_price' + i;
elCostPrice.placeholder = 'Cost Price';
elCostPrice.value = cost_price;
Cell3.appendChild(elCostPrice);
Run Code Online (Sandbox Code Playgroud)
Sat*_*pal 13
您需要使用 HTMLElement.dataset属性
该
HTMLElement.dataset属性允许以读取和写入模式访问元素上设置的所有自定义数据属性 (data-*),无论是在 HTML 还是在 DOM 中。
elCostPrice.dataset.num = i;
Run Code Online (Sandbox Code Playgroud)
有两种方式:
使用setAttribute: elCostPrice.setAttribute("data-num", i);
使用dataset:elCostPrice.dataset.num = i;
| 归档时间: |
|
| 查看次数: |
5874 次 |
| 最近记录: |