我正在创建一个从 JSON 文件动态加载内容的系统。JSON 文件描述了由 jQuery 创建的内容。我正在尝试动态添加事件。它正在工作,但如果我尝试将事件添加到两个或更多新的 dom 元素,它们都会得到最后添加的任何事件。我想我在引用我的新 dom 事件时做错了,但不知道是什么......
JSON 内容的部分示例是:
{
"container" : {
"id" : "container",
"dom_type" : "<div>",
"attr" : {
"class" : "container",
"id" : "container"
},
"children" : {
"input_submit" : {
"dom_type" : "<button>",
"html" : "Submit",
"attr" : {
"type" : "submit",
"id" : "submit",
"class" : "submit"
},
"event": {
"type": "submit",
"name": "submitevent"
}
},
"input_cancel" : {
"dom_type" : "<button>",
"html" : "Cancel",
"attr" : {
"type" : "submit",
"id" : "cancel",
"class" : "submit"
},
"event": {
"type": "submit",
"name": "cancelevent"
}
}
}
}
现在,我的函数读取 JSON 文件,jquery 使它成为一个对象,并使用一系列 if/then 语句,我创建了一些 dom 并插入它:
// here, json is a JavaScript object made by jQuery with getJson..
function makeDom (json, dom_container) {
for (var child in json.children)
{
var tp = json.children[child];
// make dom element and add id (id is required)
if (!tp['attr'])
{
$.error('jquery.myplugin.loadscreen() - erreur: Required child object "attr" not found in ' + child + '.')
}
if (undefined == tp['attr']['id'])
{
$.error('jquery.myplugin.loadscreen() - erreur: Required parameter "id" not found in "attr" in ' + child + '.');
}
// ---------------------------------------------------------------
// I guess there is something wrong with this 'el' variable, because
// when I add the event to it, all similar elements get the event
// ----------------------------------------------------------------
//add ID
var el = $(tp['dom_type']);
el.attr('id', tp['attr']['id']);
// add type if any
if (tp['attr']['type']) {
el.attr('type', tp['attr']['type'])
}
// add for if any
if (tp['attr']['for']) {
el.attr('for', tp['attr']['for'])
};
// add class if any
if (tp['attr']['class']) {
el.addClass(tp['attr']['class']);
}
// add src if any
if (tp['attr']['src']) {
el.attr('src', tp['attr']['src'])
};
// add href if any
if (tp['attr']['href']) {
el.attr('href', tp['attr']['href'])
};
// add html if any
if (tp['html']) {
el.html(tp['html']);
};
// add value if any
if (tp['attr']['value']) {
el.attr('value', tp['attr']['value']);
};
// add event if any
if (tp['event']) {
el.bind(tp['event']['type'], function(e){
//do something;
});
dom_container.append(el);
}
然后,会发生什么情况是两个按钮都获得了“取消”事件,因为它是最后添加的......我怎样才能让这个“el”变量指向正确的 DOM 元素?