javascript - 如何将javascript代码与dom元素关联起来?

标签 javascript jquery html

我有各种 dom 元素,它们的内容在页面加载时更新。通常,它们通过 ajax 使用来自服务器的数据进行更新。它们通常显示图表和表格信息等内容。

为了保持简洁,我重复使用了为常见任务(例如显示图表)生成最终 html 的代码。我将选项放在 html 属性中,并有一个数据 url 属性。例如

<div class="standard_chart"
     chart_title="Trend of X vs. Y"
     data_url="/data/x_vs_y"></div>

这个组织显着改进了我的 js 代码。

问题

有时我需要先处理数据。例如,要过滤它:

var filter_outliers_for_x_vs_y_data = function(data){
    data = data.filter(function(d){
        return -1000 < d.y && d.y < 1000;
    });
    return data;
};

我不愿意在 div 上放置 id 属性,只是为了重写该特定 dom id 的数据处理函数。考虑一下:

$(document).ready(function(){
    $('#my_x_vs_y_chart').each(function(){
         // ... reworked code just for this element
    });
});

我更愿意在该 html 文档中将预处理函数放在 html 元素旁边(或其中)。这似乎是最好的地方。

将 javascript 与特定 dom 元素关联起来的最佳方式是什么?

到目前为止我的想法:

1.
<div class="standard_chart"
     chart_title="Trend of X vs. Y"
     data_url="/data/x_vs_y"
     pre_process_fn="...some js code..."></div>
// then use `eval` to use the js code in the attribute


2.
<div class="standard_chart"
     chart_title="Trend of X vs. Y"
     data_url="/data/x_vs_y"
     pre_process_fn="...some js code...">
    <pre_process_fn>
        <script>... function definitions ... </script>
    </pre_process_fn>
</div>
// then somehow get and associate the js internal to the element

我不确定其他选项是什么,以及它们的相对好处是什么。

最佳答案

您可以使用这个想法,无需将 javascript 渲染到属性中,而是使用 fn 名称:

<div class="standard_chart"
     chart_title="Trend of X vs. Y"
     data_url="/data/x_vs_y"
     preprocess_fn="preprocess_x_vs_y"></div>

然后定义一个包含预处理器函数的对象:

var preprocessors = {
    "preprocess_x_vs_y": function () {
        var dataUrl = $(this).attr("data_url");
        var chartTitle = $(this).attr("chart_title");
        // do the processing
    }
};

var preprocessors = { }; 预定义时(在 head 部分),您还可以稍后将函数渲染到 html 脚本元素中:

<script type="text/javascript">
preprocessors["preprocess_x_vs_y"] = function () {
    var dataUrl = $(this).attr("data_url");
    var chartTitle = $(this).attr("chart_title");
    // do the processing
};
</script>

现在在文档就绪事件中,执行

$(document).ready(function () {
    $('.standard_chart').each(function () {
         var preproc_fn = $(this).attr("preprocess_fn");

         // now call the preprocessor (with this === dom element)
         if (preprocessors[preproc_fn] instanceof Function) {
             preprocessors[preproc_fn].call(this);
         }

    });
});

关于javascript - 如何将javascript代码与dom元素关联起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18174230/

相关文章:

javascript - 以编程方式切换 jquery TreeView 项目?

javascript - 滚动显示不工作

html - 在 NodeJS 提供的静态 html 中显示本地镜像

javascript - 从我的 Div background-image 属性中循环 3 个图像

javascript - 在 Javascript 中重置定时器

javascript - 在选择更改时替换 href

html - 如何同时拥有水平和垂直导航栏

javascript - 如何通过在输入中输入视频ID来嵌入YouTube视频?

javascript - 如何获取动态创建的DropDownList的ID并检查其值是否改变?

javascript - 使用 JS 将行添加到 html 表格