我有以下事件:
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,其中包含图像。创建新项目后,单击事件将停止工作。
我怎样才能update
这个绑定?
Thanks.
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');
}
});
});
EDIT:如果您的点击目标中可能有嵌套项目,那么您将需要采取稍微(但不是很多)更高级的方法,并在点击事件从被点击的元素中冒泡时查找您的目标(使用事件对象.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');
}
});
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)