数据集属性 - get/set 正确的驼峰命名法

dataset attributes - get/set correct camel case name

我将属性名称存储在字符串中的某处,需要一种方法来创建更正的名称以用于 dataset api。我得到那些属性样式的名称,例如 data-attrib-name。所以我需要将它们转换为驼峰式并删除它前面的data-

我目前找到的最短路径是下面的更新。但这对我来说有点 hacky。我的任务有更好的解决方案/更短的方法吗?

console.log(
  "data-my-test-name"
    .replace('data-', '')
    .replace(/-([a-z]?)/g, (m, g) => g.toUpperCase())
);

您可以直接将 setAttribute 与属性一起使用,而无需使用 dataset

var attr = "data-attrib-name";
document.getElementById("f1").setAttribute(attr, "changed"); 

各种方法:

console.log(document.getElementById("f1").dataset);
var attr = "data-attrib-name";

document.getElementById("f1").setAttribute(attr, "changed"); // set the attribute

console.log(document.getElementById("f1").dataset);

var datasetByAttr = document.querySelector("[" + attr + "]").dataset;
console.log(datasetByAttr);
<input type="text" id="f1" data-set-name="set" data-attrib-name="attr" />

如果您必须使用驼峰式大小写,您可以在您创建的元素上使用 dataset

var attr = "data-attrib-name",
    test = document.createElement("span");

test.setAttribute(attr, 1)
var camelCase = Object.keys(test.dataset)[0];
test = null;
console.log(camelCase);

这里是一个例子,通过属性和数据集设置和获取。

const sets = [
  {name: "data-my-test", value: "value 1"},
  {name: "data-another-test", value: "value 2"}
];


const d = document.querySelector("div");

sets.forEach(i => d.setAttribute(i.name, i.value));

console.log(d.dataset);
<div>
  look at my data attributes, via inpector.
</div>