追加身体后,YUI('click')甚至不起作用

时间:2016-05-12 05:54:12

标签: javascript yui

您好我一直在尝试使用html模板和js构建我的DOM,但我对此代码有问题。;

 YUI().use(
          'aui-modal',
          'stylesheet',
          'aui-io-request',
          function(Y) {
              var officers;
              Y.io.request('https://demo6120867.mockable.io/cmdOfficers', {
                   method: 'GET',
                   dataType: 'json',
                   on: {
                       success:function() {

                           officers = this.get('responseData').officers;
                           for(var i=0;i<officers.length;i++){
                          var template = Y.one("#officerTemplate")
                           var officerName = template.one("#officerName");
                           var officerDepartment = template.one("#department");
                           var officerId;
                           officerName.set('innerText',officers[i].officerName);

                           officerDepartment.set('innerText',officers[i].department);
                           var buttonHolder = template.one("#action_buttons")
                           var officerButtons = buttonHolder.all(".hp");

                           console.log("Officer Buttons")
                           console.log(officerButtons[0]);
                           console.log("Officer Buttons all");
                           console.log(officerButtons);
                           officerButtons.each(function(buttonNode,index){
                               console.log(buttonNode);
                               officerId = officers[i].id;
                               var data = buttonNode.getData("id");
                               // This will not get store in dom.
                               buttonNode.setData("id",i+"_"+index);
                               buttonNode.setData("officer_id",officerId);
                               console.log(buttonNode.getData("id"));
                           });
                           var bodyNode = Y.one(document.body);
                           var newItem = Y.Node.create(template.getContent()).setStyle("display","block");;
                           newItem.set('id','officer_'+i);
                           bodyNode.append(newItem);
                           // when we have template we can insert our data and append to dom.
                           }
                        }
                   }
             });

你看到的最后一行代码是附加正文,所以当我打电话时我期待

 Y.all(".hp").on("click",function(e){
                 console.log("clicked");

点击功能不起作用,我该如何解决这个问题。

感谢。

1 个答案:

答案 0 :(得分:1)

看起来这可能是event delegation的完美案例。由于问题中的元素在约束事件时尚未在DOM中。

Y.one(document.body).delegate("click", function(e) {
                 console.log("clicked");
                }, ".hp");

可以使用包含.hp元素的最近父级替换文档正文。

https://davidwalsh.name/event-delegate