最新版的prototype是1.5,查了一下有关prototype的资料,发现它的API docs整的不错,写的很清楚,那就不多
说了,依葫芦划瓢,照翻一点吧 http://www.prototypejs.org/api
第一章. Utility Methods
1. $
$() 相当于 document.getElementById()
例如以下两行相等:
Element.hide('itemId');
$('itemId').hide();
下面两行也相等:
['item1', 'item2', 'item3'].each(Element.hide);
$('item1', 'item2', 'item3').invoke('hide');
- <HTML>
- <head>
- <title>test prototype.js title>
- <script src='prototype.js'>
- script>
- head>
- <body>
- test here
- <div id='div1'>
- <a href='http://clarancepeng.javaeeye.com' target='_blank'>clarancepeng blog a>
- nothing
- div>
- <form name='testform'>
- <input type='button' name='testP' onclick='alert($("div1").innerHTML)' value='test prototype'>
- form>
- body>
- HTML>
2. $$
$$(cssRule...) -> [HTMLElement...]
$$ 相当于 document.getElementsByTagName() 或者 document.getElementsByClassName()
例:
$$('div')
// -> all DIVs in the document. Same as document.getElementsByTagName('div')!
$$('#contents')
// -> same as $('contents'), only it returns an array anyway.
$$('li.faux')
// -> all LI elements with class 'faux'
$$('#contents a[rel]')
// -> all links inside the element of ID "contents" with a rel attribute
$$('a[href="#"]')
// -> all links with a href attribute of value "#" (eyeew!)
$$('#navbar li', '#sidebar li')
// -> all links within the elements of ID "navbar" or "sidebar"
3. $A
$A(iterable) -> actualArray
它能返回数组,$$不能
var paras = $A(document.getElementsByTagName('p'));
paras.each(Element.hide);
$(paras.last()).show();
$A(document.getElementsByTagName('p')).map(Element.extend).invoke('hide');
// The hard way...
function showArgs() {
alert(Array.prototype.join.call(arguments, ', '));
}
// The easy way...
function showArgs() {
alert($A(arguments).join(', '));
}
4. $F
$F(element) -> value
5. $H
6. $R 返回数组, exclusion默认值为false包含start, end
$R(start, end[, exclusive = false]) -> ObjectRange
7. $W 转换字符串成数组, 有点类似split
$w(String) -> Array
$w('apples bananas kiwis')
// -> ['apples', 'bananas', 'kiwis']
$w("apples bananas kiwis")[0]
8. Try.these 有点类似 try {} catch(e) { }, 返回内部涵数的第一个结果
Try.these(Function...) -> firstOKResult
getTransport: function() {
return Try.these(
function() { return new XMLHttpRequest() },
function() { return new ActiveXObject('Msxml2.XMLHTTP') },
function() { return new ActiveXObject('Microsoft.XMLHTTP') }
) || false;
}
9. document.getElementsByClassName 返回用相同CSS修饰的元素
document.getElementsByClassName(className[, element]) -> [HTMLElement...]
- List item 1
- List item 2
- List item 3
document.getElementsByClassName('foo');
// -> [HTMLElement, HTMLElement] (div#one, div#two)
document.getElementsByClassName('thud');
// -> [HTMLElement, HTMLElement, HTMLElement] (div#two, li#item_one, li#item_two);
document.getElementsByClassName('thud', $('list'));
// -> [HTMLElement, HTMLElement] (li#item_one, li#item_two)
第二章 AJAX
1. 公用的选项(Common options)
选项 : 默认值 : 描述
asynchronous : true : 决定XMLHttpRequest是同步还是异步, 一般只允许用异步
contentType : 'application/x-www-form-urlencoded' : 你请求的Content-Type头类型, 如果想发送XML则需要改变这个值
encoding : 'UTF-8' : 最好保留不变
method : 'post' : 内容提交的方式, 也可以以'get'方式提交
parameters : '' : 编码成URL的参数, 以get方式提交
postBody : None : 以post方式提交时, 提交的内容, 如果没有指定, 则用parameters内容代替
requestHeaders : : 省略了, 用时再看
2. 公用的回调
回调方法 : 描述
onComplete : request完成的时候调用
onException : 如果有XHR错误产生的时候调用
onFailure : 请求完成, 并且状态码不是 2xy时调用
onInteractive : 交换过程中, 正在响应, 发送一部分包过来了, 但是没有最后结束
onLoaded : XHR对象被设置, 连接被开放, 并且准备发送request时
onLoading : XHR对象正在被设置, 并且连接打开
onSuccess : 请求完成, 并且返回状态是 2xy, 发生在onComplete之前
onUninitialized : 发生在XHR对象刚好创建的时候
onXYZ : XYZ是响应的返回的状态码, 在响应刚好完成时调用, 不过它会阻止onSuccess/ onFailure的调用, 发生在onComplete之前
3. 响应者的回调
onCreate
onComplete
onException
onInteractive
onLoaded
onLoading
onUninitialized
4. Ajax.PeriodicalUpdater 定期的调用这个方法, 根据请求得到的数据更新显示的内容
new Ajax.PeriodicalUpdater(container, url[, options])
new Ajax.PeriodicalUpdater('items', '/items', {
method: 'get', frequency: 3, decay: 2
});
5. Ajax.Request 初始化并且处理一个AJAX请求
new Ajax.Request(url[, options])
var url = '/proxy?url=' + encodeURIComponent('http://www.google.com/search?q=Prototype');
// notice the use of a proxy to circumvent the Same Origin Policy.
new Ajax.Request(url, {
method: 'get',
onSuccess: function(transport) {
var notice = $('notice');
if (transport.responseText.match(/href="http:\/\/prototypejs.org/))
notice.update('Yeah! You are in the Top 10!').setStyle({ background: '#dfd' });
else
notice.update('Damn! You are beyond #10...').setStyle({ background: '#fdd' });
}
});
6. Request life-cycle
1) XMLHttpRequest 定义的生命周期
1. Created
2. Initialized
3. Request sent
4. Response being received (can occur many times, as packets come in)
5. Response received, request complete
2) Prototype的AJAX定义的生命周期
1. onCreate (this is actually a callback reserved to AJAX global responders)
2. onUninitialized (maps on Created)
3. onLoading (maps on Initialized)
4. onLoaded (maps on Request sent)
5. onInteractive (maps on Response being received)
6. onXYZ (numerical response status code), onSuccess or onFailure (see below)
7. onComplete
// This is too bad, there's better!
new Ajax.Request('/your/url', {
onComplete: function(transport) {
if (200 == transport.status)
// yada yada yada
}
});
new Ajax.Request('/your/url', {
onSuccess: function(transport) {
// yada yada yada
}
});
7. 取得HTTP 响应头
var myRequest = new Ajax.Request('/your/url', {
onSuccess: function() {
// Note how we brace against null values
if ((myRequest.getHeader('Server') || '').match(/Apache/))
++gApacheCount;
// Remainder of the code
}
});
8. 返回JSON头
new Ajax.Request('/your/url', {
onSuccess: function(transport, json) {
// Remainder of the code
}
});
9. Ajax.Responders (AJAX请求的每个步骤的监听通知, 它是整个监听头端)
Ajax.Responders.register(responder)
Ajax.Responders.unregister(responder)
Ajax.Responders.register({
onCreate: function() {
Ajax.activeRequestCount++;
},
onComplete: function() {
Ajax.activeRequestCount--;
}
});
10. Ajax.Updater
new Ajax.Updater(container, url[, options])
new Ajax.Updater('items', '/items', {
parameters: { text: $F('text') }
});
new Ajax.Updater('items', '/items', {
parameters: { text: $F('text') },
insertion: Insertion.Bottom
});
new Ajax.Updater({ success: 'items', failure: 'notice' }, '/items', {
parameters: { text: $F('text') },
insertion: Insertion.Bottom
});
第三章 数组(Array)
1. 一个数组的遍历
You can revert to vanilla loops:
for (var index = 0; index < myArray.length; ++index) {
var item = myArray[index];
// Your code working on item here...
}
Or you can use iterators, such as each :
myArray.each(function(item) {
// Your code working on item here...
});
2. clear 清空数组
clear() -> Array
var guys = ['Sam', 'Justin', 'Andrew', 'Dan'];
guys.clear();
// -> []
guys
// -> []
3. clone 数组克容
var fruits = ['Apples', 'Oranges'];
var myFavs = fruits.clone();
myFavs.pop();
// fruits -> ['Apples', 'Oranges']
// myFavs -> ['Apples']
4. compact 压缩数组中的''/null项
['frank', , 'sue', , 'sally', null].compact()
// -> ['frank', 'sue', 'sally']
5. each 遍历数组
6. first 数组的第一个值
['Ruby', 'Php', 'Python'].first()
// -> 'Ruby'
[].first()
// -> undefined
7. flatten 压平数组项
['frank', ['bob', 'lisa'], ['jill', ['tom', 'sally']]].flatten()
// -> ['frank', 'bob', 'lisa', 'jill', 'tom', 'sally']
8. from Array.from()是$A的别名
Array.from(iterable) -> actualArray
9. indexOf 当前值在数组中的位置
[3, 5, 6, 1, 20].indexOf(1)
// -> 3
[3, 5, 6, 1, 20].indexOf(90)
// -> -1
[0, false, 15].indexOf(false)
// -> 0 instead of 1, because 0 == false!
10. inspect
['Apples', {good: 'yes', bad: 'no'}, 3, 34].inspect()
// -> "['Apples', [object Object], 3, 34]"
11. last 数组的最后一个值
['Ruby', 'Php', 'Python'].last()
// -> 'Python'
[].last()
// -> undefined
12. reduce 数组只有一个元素就返回这个元素的值, 否则就返回这个数组
reduce() -> Array | singleValue
[3].reduce(); // -> 3
[3, 5].reduce(); // -> [3, 5]
13. reverse 数组中的元素反转
reverse([inline = true]) -> Array
var nums = [3, 5, 6, 1, 20];
nums.reverse(false) // -> [20, 1, 6, 5, 3]
nums // -> [3, 5, 6, 1, 20]
nums.reverse() // -> [20, 1, 6, 5, 3]
nums // -> [20, 1, 6, 5, 3]
14. size
size() -> Number
数组的长度
15. toArray 产生一个新的数组, 类似于clone
16. uniq 去掉数组中的重复项
uniq() -> newArray
['Sam', 'Justin', 'Andrew', 'Dan', 'Sam'].uniq();
// -> ['Sam', 'Justin', 'Andrew', 'Dan']
['Prototype', 'prototype'].uniq();
// -> ['Prototype', 'prototype'] because String comparison is case-sensitive
17. without 去掉数组中的某一项
without(value...) -> newArray
[3, 5, 6, 1, 20].without(3)
// -> [5, 6, 1, 20]
[3, 5, 6, 1, 20].without(20, 6)
// -> [3, 5, 1]
第四章 Class
create
create() -> Function
var Animal = Class.create();
Animal.prototype = {
initialize: function(name, sound) {
this.name = name;
this.sound = sound;
},
speak: function() {
alert(name + " says: " + sound + "!");
}
};
var snake = new Animal("Ringneck", "hissssssssss");
snake.speak();
// -> alerts "Ringneck says: hissssssssss!"
var Dog = Class.create();
Dog.prototype = Object.extend(new Animal(), {
initialize: function(name) {
this.name = name;
this.sound = "woof";
}
});
var fido = new Dog("Fido");
fido.speak();
// -> alerts "Fido says: woof!"
第五章 Element
<div id="message" class=""></div>
// Toggle the CSS class name of div#message
$('message').addClassName('read');
// -> div#message
// You could also use a syntactic-sugar-free version:
Element.toggleClassName('message', 'read');
// -> div#message
$('message').addClassName('read').update('I read this message!').setStyle({opacity: 0.5});
1. addClassName 为某个id增加css的class
<div id="mutsu" class="apple fruit"></div>
$('mutsu').addClassName('food')
$('mutsu').className
// -> 'apple fruit food'
$('mutsu').classNames()
// -> ['apple', 'fruit', 'food']
2. addMethods
addMethods([methods])
$(element).myOwnMethod([args...]);
Element.myOwnMethod(element|id[, args...]);
Element.addMethods({
wrap: function(element, tagName) {
element = $(element);
var wrapper = document.createElement('tagName');
element.parentNode.replaceChild(wrapper, element);
wrapper.appendChild(element);
return Element.extend(wrapper);
}
});
//增加方法
Element.addMethods({
ajaxUpdate: function(element, url, options){
element = $(element);
element.update('<img src="/images/spinner.gif" alt="loading..." />');
new Ajax.Updater(element, url, options);
return element;
}
});
//更新内容
$(element).ajaxUpdate('/new/content');
// -> HTMLElement
//等待信息返回的实现
Form.Element.Methods.processing = function(element, text) {
element = $(element);
if (element.tagName.toLowerCase() == 'input' && ['button', 'submit'].include(element.type))
element.value = typeof text == 'undefined' ? 'Please wait...' : text;
return element.disable();
};
Element.addMethods();
2. ancestors 返回上级标签数组
- <html>
- […]
- <body>
- <div id="father">
- <div id="kid">
- </div>
- </div>
- </body>
- </html>
$('kid').ancestors();
// -> [div#father, body, html] // Keep in mind that
// the `body` and `html` elements will also be included!
document.getElementsByTagName('html')[0].ancestors();
// ->
3. classNames返回修饰的css的class名
classNames(element) -> [className...]
$('mutsu').classNames()
// -> ['apple', 'fruit', 'food']
// change its class names:
$('mutsu').className = 'fruit round'
$('mutsu').classNames()
// -> ['fruit', 'round']
4. cleanWhitespace 移除元素间无用的空格
cleanWhitespace(element) -> HTMLElement
- <ul id="apples">
- <li>Mutsu</li>
- <li>McIntosh</li>
- <li>Ida Red</li>
- </ul>
var element = $('apples');
element.firstChild.innerHTML;
// -> undefined
element.cleanWhitespace();
element.firstChild.innerHTML;
// -> 'Mutsu'