【问题标题】:html "data-" attribute as javascript variablehtml“data-”属性作为javascript变量
【发布时间】:2016-07-21 22:57:06
【问题描述】:

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

我说的是这样的:

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

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

【问题讨论】:

标签: javascript jquery html custom-data-attribute


【解决方案1】:

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

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

查看这里了解更多信息:

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

编辑 --

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

【讨论】:

【解决方案2】:

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

<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 对象的变量是全局的并且可以被代码中其他地方的插件覆盖的担忧。

【讨论】:

  • 实际上这可以满足我的需要。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2017-02-25
  • 2014-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多