如何运行作为 DOM 元素中的属性嵌入的脚本?
我正在使用一个名为 d3 的出色可视化库,我发现自己的代码到处都看起来非常像以下内容:
<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? );
});
什么是合适的方法?
I'm using a great visualization library called d3 and I'm finding myself with code that looks very much like the following all over the place:
<span id="sparkline"></span>
<script type="text/javascript">
drawSparkline('#target', [10, 20, 30, 40]);
// or
drawSparkline('#target', 'http://data.com/location'));
</script>
Is there a way to make this more expressive by embedding the code that acts on the dom element directly as an attribute? Perhaps something like this:
<span onload="drawSparkline(this, [10, 20, 30, 40])"></span>
<span onload="drawSparkline(this, 'http://data.com/location')"></span>
Perhaps something like:
<span data-onload="drawSparkline(this, [10, 20, 30, 40])"></span>
With something at the beginning in jQuery like:
$(document).ready(function() {
$('*[data-onload]').each( eval the onload? );
});
What would be the appropriate way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会更明确地说明您正在编码的不同类型的数据:
然后,当您迭代它们时,检查特定类型的数据:
我还建议您查看 Sparky (位于 github< /a>)如果你愿意的话为您节省一些时间并让它们在 IE 中工作。 :)
I would be more explicit about the different types of data that you're encoding:
Then, when you're iterating over them, check for specific types of data:
I'd also suggest that you check out Sparky (it's on github) if you want to save yourself some time and have them work in IE. :)
您可以使用如下类来识别跨度,而不是使用 eval:
然后使用 jQuery:
Instead of using eval you could identify the spans with a class like this:
and then, with jQuery: