|
$(id | element) -> HTMLElement $((id | element)...) -> [HTMLElement...]
If provided with a string, returns the element in the document with matching ID; otherwise returns the passed element. Takes in an arbitrary number of arguments. All elements returned by the function are extended with Prototype DOM extensions. 1。根据对应的Id返回相应的元素。2.传入元素返回元素本身 3.使用多个ID作为参数传入,将返回一个数组,里面按参数顺序存储各个结果 |
The $ function is the cornerstone of Prototype, its Swiss Army knife. Not only does it provide a handy alias for document.getElementById, it also lets you pass indifferently IDs (strings) or DOM node references to your functions:
function foo(element) {
element = $(element); //这里的element可以是一个String字符,或一个对象
/* rest of the function... */
}
Code written this way is flexible — you can pass it the ID of the element or the element itself without any type sniffing.
Invoking it with only one argument returns the element, while invoking it with multiple arguments returns an array of elements (and this works recursively: if you're twisted, you could pass it an array containing some arrays, and so forth). As this is dependent on getElementById, W3C specs apply: nonexistent IDs will yield null and IDs present multiple times in the DOM will yield erratic results. If you're assigning the same ID to multiple elements, you're doing it wrong!
上面说明了一个应用和一个注意点
1.$('YourId').hide() : 诸如这样的应用,由$返回的结果将调用hide()进行处理,如果传入多个Id,那么将遍历$返回的数组,顺序调用 hide()
2.W3C声明:不存在的Id将返回null,存在多个相同的ID,返回的结果结果将不确定,所以不要在一个页面中使用相同的ID。在Prototype框架中传入相同Id将产生错误。
The function also extends every returned element with Element.extend so you can use Prototype's DOM extensions on it. In the following code, the two lines are equivalent. However, the second one feels significantly more object-oriented:
// Note quite OOP-like...
Element.hide('itemId');
// A cleaner feel, thanks to guaranted extension
$('itemId').hide(); //采用$,函数调用将很优雅,简洁
However, when using iterators, leveraging the $ function makes for more elegant, more concise, and also more efficient code:
//此例即讲了 传入多个参数的运用
['item1', 'item2', 'item3'].each(Element.hide);
// The better way:
$('item1', 'item2', 'item3').invoke('hide');
注: $('item1', 'item2', 'item3')将产生 [obj1,obj2,obj3],然后数组中的对象依次调用 invoke
浙公网安备 33010602011771号