gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:06:29 25 4
gpt4 key购买 nike

我有各种 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com