html "data-" 属性作为 javascript 变量

html "data-" attribute as javascript variable

是否可以将 html 数据属性注册为 javascript 变量的名称?

我说的是这样的:

<form>
  <input data-varName="test1" />
  <input data-varName="test2" />
</form>

$('form').find('input').each(function() {
  var $(this).attr('data-varName') = $(this).val();
});

目标 data 属性的正确语法是:

var myVar = $(this).data("varName");

查看此处了解更多信息:

https://api.jquery.com/data/

编辑 --

这没有解决如何设置变量名的问题,但它是针对数据属性的正确方法。

一种选择是将变量存储在一个对象中,然后使用对象表示法为变量赋值:

<form>
  <input data-varName="test1" />
  <input data-varName="test2" />
</form>

var allVariables = {};

$('form input').each(function(){
  allVariables[ $(this).data('varName') ] = $(this).val();
});

或者,简单地说 JavaScript:

Array.from( document.querySelectorAll('form input') ).forEach(function(el) {
    allVariables[ el.dataset.varName ] = el.value;
});

根据上述 HTML,将导致 allVariables 对象,如:

{
  'test1' : test1Value,
  'test2' : test2Value
}

显然,您也可以使用 window 全局对象,并将变量注册到该对象,但是这会担心 window 对象的变量是全局的,并且可以被覆盖代码中其他地方的插件。