关于点击事件的Ext JS

时间:2010-07-08 13:07:39

标签: 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');
    });

});

页面加载时效果很好。

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

我如何update这种约束?

感谢。

1 个答案:

答案 0 :(得分:12)

Ext.select选择所有元素,并在那时静态地将点击处理程序添加到它们。要使新元素具有相同的处理程序,在创建它们之后还必须将它们添加到它们中。但是,这不是最佳方法。

在这种情况下最好使用事件委托 - 向容器元素添加单击处理程序,然后根据单击的项目委派处理。这样更有效(只需要一个事件处理程序)并且更加灵活。例如,如果您的包含元素具有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');
      }
    });
});

编辑:如果您的点击目标中可能嵌套了项目,那么您需要稍微(但不是很多)更高级的方法,并在点击事件冒泡时查找您的目标来自点击的元素(使用EventObject.getTarget)。如果您的目标位于事件链中,因为它从点击的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');
      }
    });
});
相关问题