我正在使用需要填充从 cookie 中获取的值的表单。表单元素的 id 对应于 cookie 名称:
<label>ABC: </label>
<input type="text" id="ABC" />
<br />
<label>DEF: </label>
<input type="text" id="DEF" />
<br />
<label>GHI: </label>
<input type="text" id="GHI" />
<br />
<label>JKL: </label>
<input type="text" id="JKL" />
<br />
最初我只是编写了一个单独的片段来获取每个表单的 cookie 值:
var ABCdata = getCookie("ABC");
var ABCfield = document.getElementById('ABC');
ABCfield.value = ABCdata;
var DEFdata = getCookie("DEF");
var DEFfield = document.getElementById('DEF');
DEFfield.value = DEFdata;
var GHIdata = getCookie("GHI");
var GHIfield = document.getElementById('GHI');
GHIfield.value = GHIdata;
var JKLdata = getCookie("JKL");
var JKLfield = document.getElementById('JKL');
JKLfield.value = JKLdata;
但后来我想把它重写为数组和循环:
var cookienames = new Array();
cookienames[0] = "ABC";
cookienames[1] = "DEF";
cookienames[2] = "GHI";
cookienames[3] = "JKL";
for (var i=0; i<cookienames.length; i++) {
var cookienames[i]+"data" = getCookie(cookienames[i]);
var cookienames[i]+"field" = document.getElementById(cookienames[i]);
cookienames[i]+"field".value = cookienames[i]+"data";
}
不知何故,数组解决方案不起作用:表单字段没有填充数据。我怀疑,动态变量名是罪魁祸首。
处理这个问题的正确方法是什么?