【问题标题】: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
【解决方案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 对象的变量是全局的并且可以被代码中其他地方的插件覆盖的担忧。