How to pass a parameter name in JavaScript?
Is there a way to get a handler to a variable dynamically in JavaScript? I think this won't make sense so here's what I'm trying to do.
I'm using JQuery Flot to generate graphs in my web app. Everything works fine until I have two graphs in the same page.
I get the data from the database using c# and convert it into a JavaScript array and write onto the page like this.
HTML/C#:
@{
KII.Models.JsonPerformGraphData items = new KII.Models.JsonPerformGraphData();
foreach (KII.Models.PerformanceGraphItem item in Model.PerformanceGraphItems)
{
items.Add(item);
}
<script type="text/javascript">
@Html.Raw("var pgdata"+Model.Id+" = ") @Html.Raw(items.toJson()) ;
</script>
}
Then, I call a method on document ready to draw the graph
JavaScript:
if ($(".PerformanceGraph")) {
$(".PerformanceGraph").livequery(function () {
//Display the graph for risk and reward.
var options = { series: {
bars: { show: true, barWidth: 0.45, align: "center" }
},
legend: {
show: true, position: "ne", backgroundOpacity: 0, container: $("#PerformanceGraphLegend")
},
multiplebars: true
};
var dataArray = $(this).attr('data-array');//I get the name of the variable as String.
$.plot($(".PerformanceGraph"), pgdata, options);
});
}
pgdata
from javascript must match "var pgdata"+Model.Id+"
fr开发者_如何学JAVAom HTML/C#.
How can I get the variable that the HTML/C# code spits out to the HTML?
You could concatenate the variable name together and "eval" it.
http://www.w3schools.com/jsref/jsref_eval.asp
Why not something like this?
<script type="text/javascript">
var pgdata = {};
@Html.Raw("pgdata["+Model.Id+"] = ") @Html.Raw(items.toJson()) ;
</script>
and then in javascript you simply iterate over the keys in pgdata:
for (k in pgdata) {
$.plot($(".PerformanceGraph"), pgdata[k], options);
}
精彩评论