如何将javascript代码与dom元素相关联

How to associate javascript code with dom elements?

本文关键字:dom 元素 关联 代码 javascript      更新时间:2023-09-26

我有各种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);
         }
    });
});