Extjs Ext JS点击事件

Extjs Ext JS点击事件,extjs,Extjs,我有以下事件: Ext.onReady(function() { Ext.select('.gallery-item img').on('click', function(e) { Ext.select('.gallery-item').removeClass('gallery-item-selected'); Ext.get(e.target).parent().addClass('gallery-item-selected'); }); }

我有以下事件:

Ext.onReady(function() {

    Ext.select('.gallery-item img').on('click', function(e) {
        Ext.select('.gallery-item').removeClass('gallery-item-selected');
        Ext.get(e.target).parent().addClass('gallery-item-selected');
    });

});
当页面加载时,它可以正常工作

但是,我动态地创建了类库项的其他div,其中包含一个图像。创建新项目后,单击事件将停止工作

如何更新此绑定

谢谢。

Ext.select选择所有元素,并在此时静态地将单击处理程序添加到这些元素中。要使新元素具有相同的处理程序,还必须在创建新元素后将其添加到新元素中。然而,这不是一个最佳的方法

在这种情况下,最好使用事件委托-向容器元素添加一个单击处理程序,然后根据单击的项委托处理。只需要一个事件处理程序fn,这样效率更高,而且更灵活。例如,如果您的包含元素的id为“gallery ct”,则类似于:

Ext.onReady(function() {
    Ext.get('gallery-ct').on('click', function(e, t){
      // t is the event target, i.e. the clicked item.
      // test to see if it is an item of the type you want to handle
      // (it is a DOM node so first convert to an Element)
      t = Ext.get(t);
      if(t.hasClass('gallery-item'){
        // radioClass automatically adds a class to the Element
        // and removes it from all siblings in one shot
        t.radioClass('gallery-item-selected');
      }
    });
});
编辑:如果您的单击目标中可能有嵌套的项,那么您需要采取稍微高级一些的方法,在单击事件从单击的元素中冒泡出来时使用查找目标。如果您的目标在事件链中,因为它从单击的el冒出,那么您知道它仍然是有效的单击。更新代码:

Ext.onReady(function() {
    Ext.get('gallery-ct').on('click', function(e, t){
      // disregard 't' in this case -- it could be a child element.
      // instead check the event's getTarget method which will 
      // return a reference to any matching element within the range
      // of bubbling (the second param is the range).  the true param 
      // is to return a full Ext.Element instead of a DOM node
      t = e.getTarget('.gallery-item', 3, true);
      if(t){
        // if t is non-null, you know a matching el was found
        t.radioClass('gallery-item-selected');
      }
    });
});

非常感谢你。经过一些小的调整,我得到了它以满足我的需要。我感到奇怪的是,在gallery item div中单击图像不会触发gallery item click事件。