简体   繁体   English

html“data-”属性为javascript变量

[英]html “data-” attribute as javascript variable

Is it possible to register a html data-attribute as the name of a javascript variable? 是否可以将html数据属性注册为javascript变量的名称?

What I am talking about is something like this: 我所说的是这样的:

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

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

The correct syntax to target data attributes is: 目标data属性的正确语法是:

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

See here for more info: 有关详情,请参阅此处:

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

EDIT -- 编辑 -

This doesn't address the issue of how to set the variable name, but it is the correct method for targeting data attributes. 这不解决如何设置变量名称的问题,但它是用于定位数据属性的正确方法。

One option is to store your variables in an object, and then use object-notation to assign values to variables: 一种选择是将变量存储在对象中,然后使用object-notation为变量赋值:

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

var allVariables = {};

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

Or, in plain JavaScript: 或者,在纯JavaScript中:

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

Which, given the above HTML, would result in an allVariables object like: 鉴于上述HTML,将导致allVariables对象,如:

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

Obviously, you could also use the window global object, and register variables to that instead but that carries the concern that variables of the window object are global and can be over-written by plugins elsewhere in the code. 显然,您也可以使用window全局对象,并将变量注册到该对象,但这会带来担心window对象的变量是全局的,并且可以被代码中其他地方的插件覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM