problem with loop -JS
i have many pieces of code like:
<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>
i tried this loop, but i am not sure about the script. Probably i have syntax errors.
<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>
thanks
to create a variable name dynamicaly you have to use bracket notation
e.g: this['$m'+x]
or window['$m'+x]
will create a variable called $m1
where x = 1
try:
window['foo' + 'bar'] = 'hello';
alert(foobar);
By the looks of $m+x
I'm guessing that you're trying to create a variable dynamically such as $m0
to $m9
based on iterating from 0 - 10. You can't do that in Javascript as far as I'm aware it will give you an error. I suggest instead of creating a dynamic variable sort of thing why not fill the values inside an array based on the indexes of x
.
Here's something:
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]
So basically $m
will be an array with arrays. I don't know if my guess is right but I hope it gives an idea.
精彩评论