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