1

我正在使用需要填充从 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";
}

不知何故,数组解决方案不起作用:表单字段没有填充数据。我怀疑,动态变量名是罪魁祸首。

处理这个问题的正确方法是什么?

4

4 回答 4

4

你试过这个:

document.getElementById(cookienames[i]).value = getCookie(cookienames[i]);
于 2013-06-28T10:44:45.517 回答
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
}

(作为旁注,预先缓存数组的长度是一个好习惯)

于 2013-06-28T10:45:40.063 回答
2

您不能以var这种方式使用关键字动态“创建”变量。

但是由于每个全局变量都是 的属性window,因此您可以这样做:

window[cookienames[i]+"data"] = getCookie(cookienames[i]);
于 2013-06-28T10:46:19.193 回答
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;
}
于 2013-06-28T10:47:08.290 回答