代码之家  ›  专栏  ›  技术社区  ›  eisbehr

数据集属性-获取/设置正确的大小写名称

  •  9
  • eisbehr  · 技术社区  · 7 年前

    我将属性名存储在字符串中的某个位置,需要一种方法来创建用于 dataset 应用程序编程接口。我得到属性样式的名字,比如 data-attrib-name 是的。所以我需要把它们换成驼色的箱子然后把 data- 在它前面。

    我现在发现的最短的方法是在下面找我的替代品。但这种感觉 粗糙的 对我来说。有没有更好的解决方案/更短的方法来完成我的任务?

    console.log(
      "data-my-test-name"
        .replace('data-', '')
        .replace(/-([a-z]?)/g, (m, g) => g.toUpperCase())
    );
    2 回复  |  直到 7 年前
        1
  •  9
  •   eisbehr    7 年前

    你可以用 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" />

    如果您必须使用camelcase,您可以使用 数据集 在您创建的元素上;

    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);
        2
  •  2
  •   Keith    7 年前

    下面是一个通过属性数据集设置和获取的示例。

    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>