前面写的get()和query()我都省略参数了,先看看文档中的函数原型: Ext.get( Mixed el ) : Element Parameters: el : Mixed The id of the node, a DOM Node or an existing Element. Returns: Element The Element object Ext.query( String path, [Node root] ) : Array Parameters: path : String The selector/xpath query root : Node (optional) The start of the query (defaults to document). Returns: Array query函数返回的其实是一个DOM Node的数组,而Ext.get的参数el可以是DOM Node,哈哈,明白了吗?就是说要实现最灵活的取法,应该用query取到DOM Node然后交给get去变成Element。也就是: var x=Ext.query(QueryStr); //我为什么不写成内联函数形式?因为这里的x只能是一个元素,而上面那句的x是一个Array,大家自己转换和处理吧 var y=Ext.get(x); 那么接下来需要介绍QueryStr的格式(其实和jQuery里的selector的格式很像啦),至于获得Element后可以干些啥,大家自己去看ExtJS文档里关于Ext.Element的说明,我就不摘过来了。 先给一个html代码,好做演示说明 复制代码 代码如下: <html> <body> <div id="bar" class="foo"> I"m a div ==> my id: bar, my class: foo <span class="bar">I"m a span within the div with a foo class</span> <a href="http://www.extjs.com" target="_blank">An ExtJs link</a> </div> <div id="foo" class="bar"> my id: foo, my class: bar <p>I"m a P tag within the foo div</p> <span class="bar">I"m a span within the div with a bar class</span> <a href="#">An internal link</a> </div> <div name="BlueLotus7">BlueLotus7@126.com</div> </body> </hmlt>
(1)根据标记取:// 这个查询会返回有两个元素的数组因为查询选中对整个文档的所有span标签。 Ext.query("span"); // 这个查询会返回有一个元素的数组因为查询顾及到了foo这个id。 Ext.query("span", "foo");// 这会返回有一个元素的数组,内容为div标签下的p标签 Ext.query("div p"); // 这会返回有两个元素的数组,内容为div标签下的span标签 Ext.query("div span");(2)根据ID取:// 这个查询会返回包含我们foo div一个元素的数组! Ext.query("#foo"); //或者直接Ext.get("foo");(3)根据class的Name去取:Ext.query(".foo");// 这个查询会返回5个元素的数组。 Ext.query("*[class]"); // 结果: [body#ext-gen2.ext-gecko, div#bar.foo, span.bar, div#foo.bar, span.bar](4)万能法去取:(用这个方法可以通过id、name、class、css等取)// 这会得到class等于“bar”的所有元素 Ext.query("*[class=bar]"); // 这会得到class不等于“bar”的所有元素 Ext.query("*[class!=bar]"); // 这会得到class从“b”字头开始的所有元素 Ext.query("*[class^=b]"); //这会得到class由“r”结尾的所有元素 Ext.query("*[class$=r]"); //这会得到在class中抽出“a”字符的所有元素 Ext.query("*[class*=a]");//这会得到name等于“BlueLotus7”的所有元素 Ext.query("*[name=BlueLotus7]"); 我们换个html代码: 复制代码 代码如下: <html> <head> </head> <body> <div id="bar" class="foo" style="color:red;"> 我是一个div ==> 我的id是: bar, 我的class: foo <span class="bar" style="color:pink;">I"m a span within the div with a foo class</span> <a href="http://www.extjs.com" target="_blank" style="color:yellow;">An ExtJs link with a blank target!</a> </div> <div id="foo" class="bar" style="color:fushia;"> my id: foo, my class: bar <p>I"m a P tag within the foo div</p> <span class="bar" style="color:brown;">I"m a span within the div with a bar class</span> <a href="#" style="color:green;">An internal link</a> </div> </body> </html>