2011-05-14 53 views
0

我有很多代码片段,如:问题环路-js

<script type="text/javascript"> 
dojo.query("body").delegate("#input0 > select.estatistica", "onchange", function(evt){ 
     dojo.xhrPost({ 
      url: "drop2.php", 
      handleAs: "json", 
      postData: "data=" + $(this).val(), 
      preventCache: true, 
      load: function(json) { 
       $m0 = []; 

       for (var i = 1; i < 10; i++) { 
        $m0.push(parseFloat(json[i]["valor" + i])); 
       } 
       dojo.addOnLoad(refreshChar0); 

      } 
     }); 
    }); 
</script> 


<script type="text/javascript"> 
dojo.query("body").delegate("#input1 > select.estatistica", "onchange", function(evt){ 
     dojo.xhrPost({ 
      url: "drop2.php", 
      handleAs: "json", 
      postData: "data=" + $(this).val(), 
      preventCache: true, 
      load: function(json) { 
       $m1 = []; 

       for (var i = 1; i < 10; i++) { 
        $m1.push(parseFloat(json[i]["valor" + i])); 
       } 
       dojo.addOnLoad(refreshChart1); 
      } 
     }); 
    }); 
</script> 

我想这个循环中,但我不知道该脚本。可能我有语法错误。

<script type="text/javascript"> 
for(x=0; x<10; x++) { 
dojo.query("body").delegate("'#input'+x+'> select.estatistica'", "onchange", function(evt) { 
     dojo.xhrPost({ 
      url: "drop2.php", 
      handleAs: "json", 
      postData: "data=" + $(this).val(), 
      preventCache: true, 
      load: function(json) { 
       $m+x = []; 

       for (var i = 1; i < 10; i++) { 
        $m+x.push(parseFloat(json[i]["valor" + i])); 
       } 
       dojo.addOnLoad(refreshChart+x); 
      } 
     }); 
    }); 
} 
</script> 

感谢

+2

不认为我'$ m + x'是一个有效的变量 – tradyblix 2011-05-14 15:38:21

回答

0

到dynamicaly创建一个变量名,你必须使用括号记号

如:this['$m'+x]window['$m'+x]会创建一个名为$m1变量,其中x = 1

尝试:

window['foo' + 'bar'] = 'hello'; 
alert(foobar); 
+0

逐步。这是对的? .delegate(“'#input'+ x +'> select.estatistica'”, – 2011-05-14 16:29:53

+0

no。try:'.delegate(“#input”+ x +“> select.estatistica”,....' – herostwist 2011-05-14 16:45:48

+0

或更好那些输入一个类,并使用'.delegate(“input.someclassname> select.estatistica”,....' – herostwist 2011-05-14 16:49:06

0

截至$m+x我猜你想创建动态,如$m0$m9基于从0迭代变量的长相 - 10.你不能这样做在Javascript中,据我所知它会给你一个错误。我建议不要创建一个动态变量类的东西,为什么不根据x的索引填充数组内的值。

这里的东西:

var $m = []; 
for(x=0; x<10; x++) 
{ 
    // some of your codes here ... 

    // make $m[x] an array 
    if (typeof $m[x] == "undefined") 
     $m[x] = []; 

    // some of your codes here... 

    for (var i = 1; i < 10; i++) 
    { 
     // of course you need to change this to what you need to push 
     $m[x].push(i); 
    } 

} 

console.log($m[0]); // [1, 2, 3, 4, 5, 6, 7, 8, 9] 

所以基本上$m将与数组的数组。我不知道我的猜测是否正确,但我希望它能提供一个想法。