我正在创建一个系统,其中内容是从json文件动态加载的。 json文件描述了jQuery创建的内容。我正在尝试动态添加事件。它正在工作,但如果我尝试将事件添加到2个或更多新的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元素?
答案 0 :(得分:2)
el
变量由一个闭包中的所有事件处理程序共享。
您需要创建一个附加事件处理程序的单独方法,并将变量作为参数 对函数的每次调用都将为事件处理程序创建一个单独的闭包,并带有变量的单独副本。