我正在处理需要使用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";
}
不知何故,阵列解决方案不起作用:表单字段不会填充数据。我怀疑,动态变量名称是罪魁祸首。
处理此问题的正确方法是什么?
答案 0 :(得分:4)
你试过这个:
document.getElementById(cookienames[i]).value = getCookie(cookienames[i]);
答案 1 :(得分:2)
不需要在循环内使用不同的变量。试试吧
var cookienames = ["ABC", "DEF", "GHI", "JKL"],
field,
data,
cn;
for (var i = 0, cl = cookienames.length; i < cl; i++) {
cn = cookienames[i]; // get cookie name
data = getCookie(cn); // read cookie value
field = document.getElementById(cn); // retrieve field
field.value = data; // set field value
}
(作为旁注,先前缓存数组的长度是个好习惯)
答案 2 :(得分:2)
您不能以这种方式使用var
关键字动态“创建”变量。
但是因为每个全局变量都是window
的属性,所以你可以这样做:
window[cookienames[i]+"data"] = getCookie(cookienames[i]);
答案 3 :(得分:1)
不知道为什么要使用中间变量,这应该可行
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 data = getCookie(cookienames[i]);
document.getElementById(cookienames[i]).value = data;
}