如何运行作为DOM元素中的属性嵌入的脚本? [英] How to run a script embedded as an attribute in a DOM element?

查看:142
本文介绍了如何运行作为DOM元素中的属性嵌入的脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用一个名为d3的可视化库,我发现自己的代码看起来非常像下面的地方:

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>

有没有办法通过嵌入作用于dom元素的代码直接表示属性?也许这样:

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>

可能类似:

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

在jQuery的开头有一些东西:

With something at the beginning in jQuery like:

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

什么是适当的方式?

推荐答案

我会对您编码的不同类型的数据更加明确:

I would be more explicit about the different types of data that you're encoding:

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

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

Then, when you're iterating over them, check for specific types of data:

$(".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 (它是 github )if你想保存自己一些时间,让他们在IE中工作。 :)

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. :)

这篇关于如何运行作为DOM元素中的属性嵌入的脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆