In Ext JS, how to attach events to dynamic html elements?

Suppose I have some Ext JS code that attaches an event handler to all elements with class "myclass". For example:

Ext.onReady(function(){
   Ext.select('a[class*=myclass]').on('click', function(event, elm){
      // do something
   });
});

And my html might be as follows:

<a class="myclass" href="#">test1</a>
<a class="myclass" href="#">test2</a>
<a class="myclass" href="#">test3</a>

That works with no problem. However, consider if the "myclass" elements were written to the page at some future time.

For example:

<a id="anchor1" href="#">create link dynamically</a>
<script type="text/javascript">
Ext.onReady(function(){
    Ext.select('a[id*=anchor1]').on('click', function(event, elm){
        Ext.get('panel').update('<a class="myclass" href="#">test4</a>');
    });
});

In this case, the "test4" link is created when a user clicks on a#anchor1.

The "test4" link does not have the click() handler associated with it, even though it has class="myclass".

Any idea how I can fix this?

Basically, I would like to write the click() handler once and have it apply to both content present at page load, and content brought in later via Ajax/DHTML.


尝试委托下面的活动 -

       Ext.getBody().on('click', function(event, target){
        var element = Ext.get(target);
        //perform your action here

        }, null, {
       delegate: '.myclass a'
       });

Do not listen to individual items in this case but listen to their container. Then items can be freely added or removed to/from the container and your logic will still work.

I also have an example of the technique. Beware, the example has been written for a previous version of Ext so you probably cannot copy and paste its code and expect it will work today. Nevertheless, the principle is still applicable and can be used nowadays.

Link to the source code: http://examples.extjs.eu/itemclick.js

链接地址: http://www.djcxy.com/p/51460.html

上一篇: 使用匿名代理进行事件处理时的垃圾回收

下一篇: 在Ext JS中,如何将事件附加到动态html元素?