动态创建的元素上的数据属性

cha*_*lie 5 javascript

我正在动态创建元素,这是我用于一个单元格的代码。

我想添加一个带有自定义值的数据属性。

我试过了:

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)


T.J*_*der 6

有两种方式:

  1. 使用setAttributeelCostPrice.setAttribute("data-num", i);

  2. 使用datasetelCostPrice.dataset.num = i;