2011-11-18 58 views
4

我使用的是一个伟大的可视化库称为D3,我发现自己用的代码看起来非常像下面所有的地方:如何在DOM元素中运行嵌入为属性的脚本?

<span id="sparkline"></span> 
<script type="text/javascript"> 
    drawSparkline('#target', [10, 20, 30, 40]); 
    // or 
    drawSparkline('#target', 'http://data.com/location')); 
</script> 

有没有办法使这个更具表现力通过嵌入直接作为属性作用于dom元素的代码?也许是这样的:

<span onload="drawSparkline(this, [10, 20, 30, 40])"></span> 
<span onload="drawSparkline(this, 'http://data.com/location')"></span> 

也许是这样的:

<span data-onload="drawSparkline(this, [10, 20, 30, 40])"></span> 

有了开头的东西jQuery中,如:

$(document).ready(function() { 
    $('*[data-onload]').each(eval the onload?); 
}); 

什么是适当的方式吗?

回答

0

而是使用eval你可以用这样的类标识跨度:

<span class="sparkLine" data-sparkdata="[10, 20, 30, 40]"></span> 
<span class="sparkLine" data-sparkdata="http://data.com/location"></span> 

,然后,使用jQuery:

$(document).ready(function() { 
    $('.sparkLine').each(function(){ 
     drawSparkline(this, $(this).data("sparkdata")); 
    }); 
}); 
+0

有时是迷你图,其他时间是迷你饼图。对他们所有的课程看起来很奇怪。 – rmarimon

+0

噢,你可以做$('[data-sparkdata]')而不是$('sparkLine'),同样的代码也可以工作(或者,如果可以的话,$(“something”))find(' [data-sparkdata]')) – NicoSantangelo

+0

我认为这是一个很好的方法,但是请注意,您从属性中获取了一个字符串,所以在数组情况下,您需要执行类似于'JSON.parse($ (本)。数据(sparkdata))'。 – nrabinowitz

1

我会更明确一些不同类型的数据你要对其进行编码:

<span class="sparkline" data-values="10,20,30,40"></span> 
<span class="sparkline" data-url="http://data.com/location"></span> 

然后,当你遍历它们,检查特定类型的数据:

$(".sparkline").each(function() { 
    var $source = $(this), 
     values = $source.data("values"), 
     url = $source.data("url"); 
    if (values) { 
     // JSON.parse() is okay too, but if you're just 
     // encoding lists of numbers this will be faster 
     var data = values.split(", ").map(parseFloat); 
     drawSparkline(this, data); 
    } else if (url) { 
     var that = this; 
     $.ajax(url) 
      .then(function(data) { 
       drawSparkline(that, data); 
      }); 
    } 
}); 

我也建议你看看Sparky(这是on github),如果你想给自己节省一些时间,让他们在IE浏览器。 :)

相关问题