【问题标题】:How to add custom events dynamically with jQuery?如何使用 jQuery 动态添加自定义事件?
【发布时间】:2010-11-29 18:52:14
【问题描述】:

我正在创建一个从 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 元素?

【问题讨论】:

    标签: jquery jquery-events dynamic-binding


    【解决方案1】:

    el 变量由单个闭包中的所有事件处理程序共享。

    您需要创建一个单独的方法来附加事件处理程序并将变量作为参数。
    对函数的每次调用都会为事件处理程序创建一个单独的闭包,并带有一个单独的变量副本。

    【讨论】:

    • 我是否应该创建另一种方法来附加事件处理程序并将其传递给“el”和其他变量?如 if(tp['event']) { newMethod(el,eventType); } ?
    • @Regis:是的。您可以将整个循环体移动到以childjsondom_container 作为参数的函数中。
    • 只是跟进:我确实尝试过,它确实工作得很好。显然,既然我已经阅读了更多关于闭包的内容,它就更有意义了。再次感谢 SLaks!
    猜你喜欢
    • 2010-11-19
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    相关资源
    最近更新 更多