在javascript中,我正在渲染一个数据点列表,如下所示:
<ul class="site-stats">
<li>
<div data-title="Cleared Orders" data-pts="[gd(2013, 9 , 9), 3],[gd(2013, 9 , 10), 1],[gd(2013, 9 , 13), 1],[gd(2013, 9 , 16), 1]" class="cc">
<i class="icon=arrow-right"></i>
<strong>6</strong>
<small>Cleared Orders</small>
</div>
</li>
<li>
<div data-title="Customers Added" data-pts="[gd(2013, 9 , 9), 5],[gd(2013, 9 , 10), 2]" class="cc">
<i class="icon=arrow-right"></i>
<strong>7</strong>
<small>Customers Added</small>
</div>
</li>
<li>
<div data-title="Counts Ran" data-pts="[gd(2013, 9 , 9), 8],[gd(2013, 9 , 10), 11],[gd(2013, 9 , 11), 7],[gd(2013, 9 , 12), 1],[gd(2013, 9 , 16), 5]" class="cc">
<i class="icon=arrow-right"></i>
<strong>32</strong>
<small>Counts Ran</small>
</div>
</li>
<li>
<div data-title="Pending Orders" data-pts="" class="cc">
<i class="icon=arrow-right"></i>
<strong>0</strong>
<small>Pending Orders</small>
</div>
</li>
<li>
<div data-title="Failed Orders" data-pts="" class="cc">
<i class="icon=arrow-right"></i>
<strong>0</strong>
<small>Failed Orders</small>
</div>
</li>
<li>
<div data-title="Records Delivered" data-pts="[gd(2013, 9 , 9), 25970],[gd(2013, 9 , 10), 2500],[gd(2013, 9 , 13), 2023],[gd(2013, 9 , 16), 400]" class="cc">
<i class="icon=arrow-right"></i>
<strong>30893</strong>
<small>Records Delivered</small>
</div>
</li>
</ul>
基本上,data-pts保存了我的flot图表值。 Onclick我想改变我的flot图表的内容:
$(".cc").click(function(e)
{
var data = $(this).data('pts');
console.log(data);
plot.setData([data]);
plot.setupGrid();
plot.draw();
});
当我这样做时,var数据作为一个直接字符串返回...真是奇怪,是console.log(data)给了我期望的数组。当然,这会导致flot图表没有刷新新数据...是否有我将字符串转换回原始javascript数组?我也对其他建议持开放态度......
谢谢!
答案 0 :(得分:2)
你得到的是一个字符串。您可以使用eval()
来评估字符串并将其转换为对象。
var data = $(this).data('pts');
data = eval(data);
答案 1 :(得分:0)
你可以试试这个
$(function(){
$(".cc").click(function(e)
{
var data = $(this).data('pts');
if(data.length) {
var reg = /\]\,\[/;
var matches = data.replace('[','').substring(0, data.length-2).split(reg);
var arr = [];
arr = matches.map(function(i){
var a = [];
a[0] = i.substring(0, i.lastIndexOf(','));
a[1] = i.substring(i.lastIndexOf(' ')+1);
return a;
});
console.log(arr[0][0]); // gd(2013, 9 , 9)
console.log(arr[0][1]); // 3
console.log(arr[3][0]); // gd(2013, 9 , 16)
console.log(arr[3][1]); // 1
}
});
});
DEMO.
此外,eval(data)
将一起评估您的函数调用。