Microsoft ASP.NET AJAX 中有一个新的脚本方法:$get() 来获得页面元素对象(如button textbox等)的引用。
而另一个类似的方法是$find()来获得客户端的JavaScript组件引用。
$get 是getElementById 的简写,
$find 是Sys.Application.findComponent的简写。
下面是$get 的定义代码:
- var $get = Sys.UI.DomElement.getElementById = function Sys$UI$DomElement$getElementById(id, element) {
- /// <param name="id" type="String"></param>
- /// <param name="element" domElement="true" optional="true" mayBeNull="true"></param>
- /// <returns domElement="true" mayBeNull="true"></returns>
- var e = Function._validateParams(arguments, [
- {name: "id", type: String},
- {name: "element", mayBeNull: true, domElement: true, optional: true}
- ]);
- if (e) throw e;
- if (!element) return document.getElementById(id);
- if (element.getElementById) return element.getElementById(id);
- // Implementation for browsers that don't have getElementById on elements:
- var nodeQueue = [];
- var childNodes = element.childNodes;
- for (var i = 0; i < childNodes.length; i++) {
- var node = childNodes[i];
- if (node.nodeType == 1) {
- nodeQueue[nodeQueue.length] = node;
- }
- }
- while (nodeQueue.length) {
- node = nodeQueue.shift();
- if (node.id == id) {
- return node;
- }
- childNodes = node.childNodes;
- for (i = 0; i < childNodes.length; i++) {
- node = childNodes[i];
- if (node.nodeType == 1) {
- nodeQueue[nodeQueue.length] = node;
- }
- }
- }
- return null;
- }
$find
是Sys.Application.findComponent的简写.
组件和控件的典型区别在于(source: http://ajax.asp.net/docs/tutorials/CreatingCustomClientComponentsTutorial.aspx)
1.组件的实例没有具体的实体的UI(界面)表现,像timer,可以定时的引发事件,但页面上是看不到的。
2.不结合DOM元素(不理解)。
3.包含客户端代码,这些代码是可定制,可重用,跨应用程序的。
4.继承自组件基类。
下面是$find的定义代码:
- var $find = Sys.Application.findComponent;
- function Sys$_Application$findComponent(id, parent) {
- /// <param name="id" type="String"></param>
- /// <param name="parent" optional="true" mayBeNull="true"></param>
- /// <returns type="Sys.Component" mayBeNull="true"></returns>
- var e = Function._validateParams(arguments, [
- {name: "id", type: String},
- {name: "parent", mayBeNull: true, optional: true}
- ]);
- if (e) throw e;
- // Need to reference the application singleton directly beause the $find alias
- // points to the instance function without context. The 'this' pointer won't work here.
- return (parent ?
- ((Sys.IContainer.isInstanceOfType(parent)) ?
- parent.findComponent(id) :
- parent[id] || null) :
- Sys.Application._components[id] || null);
- }
推荐使用findComponent (or $find)方法来获得组件对象的引用,这些最近是应用程序通过addComponent (or $create)注册过的。
注:如果父类没有指定,检索限制在顶级组件中,如果父类指定了组件对象,检索限制在指定的组件;如果父类是一个DOM元素,检索限定在次组件的子组件或者是特定的组件上。
原文:http://blogs.msdn.com/irenak/archive/2007/02/19/sysk-290-asp-net-ajax-get-vs-find.aspx
翻译的既不够全面也不够准确,错的地方希望指出。