开发者

How can I put a variable within a Javascript document call?

I'm trying to create a string to pass to a PHP file with numerous开发者_开发技巧 variables in it. The Javascript code goes through an array of variables - the names of which correspond to checkboxes in a form on the page. If the name of the variable in the array has been checked in the form below then it adds the name of the variable to the string that gets posted to the PHP file. Here's the code:

 var datesStr = ["L2010L04L01", "L2010L04L02", "L2010L04L06", "L2011L01L07", "L2010L10L09", "L2010L07L09", "L2011L05L10"]; //etc. This is a sample; the list is much longer.
   var sendStr = "";

   for (var i in datesStr) {

   if(document.swapOptions.datesStr[i].checked == true) {
     sendStr = sendStr+"&to"+i+"="+datesStr[i];
   }

   }

But for some reason it has a problem when I put the variable into the document.swapOptions line. I've also tried this but it doesn't work:

var datesStr = ["L2010L04L01", "L2010L04L02", "L2010L04L06", "L2011L01L07", "L2010L10L09", "L2010L07L09", "L2011L05L10"]; //etc. This is a sample; the list is much longer.
   var sendStr = "";
var intermedDatesStr = "";

   for (var i in datesStr) {

   intermedDatesStr = document.swapOptions.datesStr[i];

   if(intermedDatesStr.checked == true) {
     sendStr = sendStr+"&to"+i+"="+datesStr[i];
   } 
   }

But it doesn't work either. I think the browser's looking for an object in the form called "intermedDatesStr". Is there any way to reference the object held be the variable value? Any help here would be most appreciated!

Thanks, Ben


You need to use bracket notation when accessing properties dynamically like this:

var datesStr = ["L2010L04L01", "L2010L04L02", "L2010L04L06", "L2011L01L07", "L2010L10L09", "L2010L07L09", "L2011L05L10"]; //etc. This is a sample; the list is much longer.
var sendStr = "";
var intermedDatesStr = "";
for (var i=0; i<datesStr.length; i++) {
  if(document.swapOptions[datesStr[i]].checked == true) {
    sendStr = sendStr+"&to"+i+"="+datesStr[i];
  } 
}

This accessed the properties like this:

document.swapOptions["L2010L04L01"]
//which is the same as:
document.swapOptions.L2010L04L01

The other change is using a normal for loop, a for...in loop is not the proper way to iterate through the array, you'll get other inherited properties and not necessarily the order you expect.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜