笔记 Ext.lib.Event中的getTarget方法使用
首先看下这getTarget个函数的源码, google 了一下在该函数的作用 在事件传播路径上查找满足指定选择条件的元素
Ext.lib.Event = function() { //... var pub={ //... getTarget : function(ev) { ev = ev.browserEvent || ev; return this.resolveTextNode(ev.target || ev.srcElement); }, resolveTextNode : Ext.isGecko ? function(node){ if(!node){ return; } // work around firefox bug, https://bugzilla.mozilla.org/show_bug.cgi?id=101197 var s = HTMLElement.prototype.toString.call(node); if(s == '[xpconnect wrapped native prototype]' || s == '[object XULElement]'){ return; } return node.nodeType == 3 ? node.parentNode : node; } : function(node){ return node && node.nodeType == 3 ? node.parentNode : node; } //... }; //... return pub; }();
以下是这个函数的几个例子
example one: finding the clicked element
<div id="wrapper"> <a href="javascript:;" title="click 1">click 1</a> <a href="javascript:;" title="click 2">click 2</a> </div>
<script type="text/javascript"> Ext.onReady(function () { Ext.fly('wrapper').on('click', function (evt) { var target = evt.getTarget(); console.log('You clicked on',target.innerHTML); }); }); </script>
给warpper绑定click事件,当单击其内部的两个链接时候,根据W3C dom 事件处理机制,则会触发其click事件,当鼠标单击第一个链接click 1时候,firebug的控制台打印出如下消息
![](https://pic002.cnblogs.com/images/2011/112331/2011031716274526.png)
同样的当单击第二个链接click 2的时候,firebug的控制台打印出如下消息
![](https://pic002.cnblogs.com/images/2011/112331/2011031716360234.png)
example two: finding the parent element
<div id="wrapper"> <a href="javascript:;" title="error_tips" id="error_tips"><img src="/html3/error_tips.gif" alt="error_tips" style="border:1px solid green"/></a> </div>
<script type="text/javascript"> Ext.onReady(function () { Ext.fly('wrapper').on('click', function (evt) { var targetEl = Ext.fly(evt.getTarget()); var anchor = targetEl.up("a"); console.log(anchor.getAttribute('id')); }); }); </script>
此时的页面呈现如下图所示
![](https://pic002.cnblogs.com/images/2011/112331/2011031716522933.png)
当单击图片的时候,firebug的控制台打印出如下消息
![](https://pic002.cnblogs.com/images/2011/112331/2011031716552624.png)
从控制台打印出的消息很容易明白up方法,找其父元素
example three:Corresponding Record Reference
<div id="wrapper"> <a href="javascript:;" title="click 1" ext:recordId="1">click 1</a> <a href="javascript:;" title="click 2" ext:recordId="2">click 2</a> </div>
<script type="text/javascript"> Ext.onReady(function () { Ext.fly('wrapper').on('click', function (evt) { var target =Ext.fly(evt.getTarget()); console.log("You clicked on record: ", target.getAttributeNS('ext', 'recordId')); }); }); </script>
此时单击第一链接click 1时,firebug控制台打印出如下消息
![](https://pic002.cnblogs.com/images/2011/112331/2011031717130174.png)
当有一组的相同的元素时候,参照上面的代码就可以区别出不同的元素。