Prototype1.4手冊
prototype.js開發(fā)者手冊
對應(yīng)版本1.4.0
看到一個很好的東西在國內(nèi)沒有被很多人使用起來,實在是不爽,所以花了很大功夫把這個手冊翻譯成中文,由于這篇文章很長,所以,翻譯的工作量很大而且有些地方英文版也沒有說清楚,雖得查看源代碼,好在不是堅持做完了,大家鼓勵下??!^o^
prototype.js是一個非常優(yōu)雅的javascript基礎(chǔ)類庫,對javascript做了大量的擴展,而且很好的支持Ajax,國外有多個基于此類庫實現(xiàn)的效果庫,也做得很棒。
prototype.js不僅是一個有很大實用價值的js庫,而且有很高的學(xué)習(xí)價值,所以我強烈建議B/S開發(fā)人員和對JS開發(fā)感興趣的朋友去瀏覽一些它的源代碼,其中有很多的珠璣,你絕對會覺得讀它的源代碼是一種享受,當(dāng)然要讀得懂,呵呵。
網(wǎng)上也有人寫過1.3版的源碼解讀,大家可以找來看看。不過1.4版做了很大的擴充,所以希望有朋友寫出1.4版的源碼解讀。
幾點說明:
prototype.js是什么?
萬一你沒有使用過大名鼎鼎的prototype.js,那么讓我來告訴你,prototype.js是由Sam Stephenson寫的一個javascript類庫。這個構(gòu)思奇妙,而且兼容標(biāo)準(zhǔn)的類庫,能幫助你輕松建立有高度互動的web2.0特性的富客戶端頁面。
如果你最近嘗試使用它,你大概了解到文檔并不是作者的一個強項。和在我以前使用這個類庫的不少開發(fā)者一樣,一開始,我不得不一頭扎進閱讀prototype.js的源代碼和實驗它的功能中。我想,在我學(xué)習(xí)完它之后,把我學(xué)到的東西分享給大家是件不錯的事。
同時,在本文中,我也將提供一個關(guān)于這個類庫提供的objects,classes,functions,extensions這對東東的非官方參考
在閱讀這個文檔時,熟悉Ruby的開發(fā)者將會注意到Ruby的一些內(nèi)建類和本類庫擴展實現(xiàn)之間非常相似。
相關(guān)文章
Advanced JavaScript guide.
一些實用的函數(shù)
這個類庫帶有很多預(yù)定義的對象和實用函數(shù),這些東東的目的顯然是把你從一些重復(fù)的打字中解放出來 。
使用$()方法
$() 方法是在DOM中使用過于頻繁的 document.getElementById() 方法的一個便利的簡寫,就像這個DOM方法一樣,這個方法返回參數(shù)傳入的id的那個元素。
比起DOM中的方法,這個更勝一籌。你可以傳入多個id作為參數(shù)然后 $() 返回一個帶有所有要求的元素的一個 Array 對象。
<HTML> <HEAD> <TITLE> Test Page </TITLE> <script src="prototype-1.3.1.js"></script> <script> function test1() { var d = $('myDiv'); alert(d.innerHTML); } function test2() { var divs = $('myDiv','myOtherDiv'); for(i=0; i<divs.length; i++) { alert(divs[i].innerHTML); } } </script> </HEAD> <BODY> <div id="myDiv"> <p>This is a paragraph</p> </div> <div id="myOtherDiv"> <p>This is another paragraph</p> </div> <input type="button" value=Test1 onclick="test1();"><br> <input type="button" value=Test2 onclick="test2();"><br> </BODY> </HTML>
另外一個好處是,這個函數(shù)能傳入用string表示的對象ID,也可以傳入對象本身,這樣,在建立其它能傳兩種類型的參數(shù)的函數(shù)時非常有用。
使用$F()函數(shù)
$F()函數(shù)是另一個大收歡迎的“快捷鍵”,它能用于返回任何表單輸入控件的值,比如text box,drop-down list。這個方法也能用元素id或元素本身做為參數(shù)。
<script>
function test3()
{
alert( $F('userName') );
}
</script>
<input type="text" id="userName" value="Joe Doe"><br>
<input type="button" value=Test3 onclick="test3();"><br>
使用$A()函數(shù)
$A()函數(shù)能把它接收到的單個的參數(shù)轉(zhuǎn)換成一個Array對象。
這個方法,結(jié)合被本類庫擴展了的Array類,能方便的把任何的可枚舉列表轉(zhuǎn)換成或拷貝到一個Array對象。一個推薦的用法就是把DOM Node Lists轉(zhuǎn)換成一個普通的Array對象,從而更有效率的進行遍歷,請看下面的例子。
<script> function showOptions(){ var someNodeList = $('lstEmployees').getElementsByTagName('option'); var nodes = $A(someNodeList); nodes.each(function(node){ alert(node.nodeName + ': ' + node.innerHTML); }); } </script> <select id="lstEmployees" size="10" > <option value="5">Buchanan, Steven</option> <option value="8">Callahan, Laura</option> <option value="1">Davolio, Nancy</option> </select> <input type="button" value="Show the options" onclick="showOptions();" >
使用 $H() 函數(shù)
$H()函數(shù)把一些對象轉(zhuǎn)換成一個可枚舉的和聯(lián)合數(shù)組類似的Hash對象。
<script>
function testHash()
{
//let's create the object
var a = {
first: 10,
second: 20,
third: 30
};
//now transform it into a hash
var h = $H(a);
alert(h.toQueryString()); //displays: first=10&second=20&third=30
}
</script>
使用$R()函數(shù)
$R()是new ObjectRange(lowBound,upperBound,excludeBounds)的縮寫。
跳到ObjectRange 類文檔可以看到一個關(guān)于此類的完整描述. 此時,我們還是先來看一個例子以展示這個縮寫能代替哪些方法吧。其它相關(guān)的一些知識可以在Enumerable 對象文檔中找到。
<script>
function demoDollar_R(){
var range = $R(10, 20, false);
range.each(function(value, index){
alert(value);
});
}
</script>
<input type="button" value="Sample Count" onclick="demoDollar_R();" >
使用Try.these()函數(shù)
Try.these() 方法使得實現(xiàn)當(dāng)你想調(diào)用不同的方法直到其中的一個成功正常的這種需求變得非常容易, 他把一系列的方法作為參數(shù)并且按順序的一個一個的執(zhí)行這些方法直到其中的一個成功執(zhí)行,返回成功執(zhí)行的那個方法的返回值。
在下面的例子中, xmlNode.text在一些瀏覽器中好用,但是xmlNode.textContent在另一些瀏覽器中正常工作。 使用Try.these()方法我們可以得到正常工作的那個方法的返回值。
<script>
function getXmlNodeValue(xmlNode){
return Try.these(
function() {return xmlNode.text;},
function() {return xmlNode.textContent;)
);
}
</script>
Ajax對象
上面提到的共通方法非常好,但是面對它吧,它們不是最高級的那類東西。它們是嗎?你很可能自己編寫了這些甚至在你的腳本里面有類似功能的方法。但是這些方法只是冰山一角。
我很肯定你對prototype.js感興趣的原因很可能是由于它的AJAX能力。所以讓我們解釋當(dāng)你需要完成AJAX邏輯的時候,這個包如何讓它更容易。
Ajax 對象是一個預(yù)定義對象,由這個包創(chuàng)建,為了封裝和簡化編寫AJAX 功能涉及的狡猾的代碼。 這個對象包含一系列的封裝AJAX邏輯的類。我們來看看其中幾個類。
使用Ajax.Request類
如果你不使用任何的幫助程序包,你很可能編寫了整個大量的代碼來創(chuàng)建XMLHttpRequest對象并且異步的跟蹤它的進程, 然后解析出響應(yīng) 然后處理它。當(dāng)你不需要支持多于一種類型的瀏覽器時你會感到非常的幸運。
為了支持 AJAX 功能。這個包定義了 Ajax.Request 類。
假如你有一個應(yīng)用程序可以通過url http://yoursever/app/get_sales?empID=1234&year=1998與服務(wù)器通信。它返回下面這樣的XML 響應(yīng)。
<?xml version="1.0" encoding="utf-8" ?> <ajax-response> <response type="object" id="productDetails"> <monthly-sales> <employee-sales> <employee-id>1234</employee-id> <year-month>1998-01</year-month> <sales>$8,115.36</sales> </employee-sales> <employee-sales> <employee-id>1234</employee-id> <year-month>1998-02</year-month> <sales>$11,147.51</sales> </employee-sales> </monthly-sales> </response> </ajax-response>
用 Ajax.Request對象和服務(wù)器通信并且得到這段XML是非常簡單的。下面的例子演示了它是如何完成的。
<script> function searchSales() { var empID = $F('lstEmployees'); var y = $F('lstYears'); var url = 'http://yoursever/app/get_sales'; var pars = 'empID=' + empID + '&year=' + y;var myAjax = new Ajax.Request( url, { method: 'get', parameters: pars, onComplete: showResponse });} function showResponse(originalRequest) { //put returned XML in the textarea $('result').value = originalRequest.responseText; } </script> <select id="lstEmployees" size="10" onchange="searchSales()"> <option value="5">Buchanan, Steven</option> <option value="8">Callahan, Laura</option> <option value="1">Davolio, Nancy</option> </select> <select id="lstYears" size="3" onchange="searchSales()"> <option selected="selected" value="1996">1996</option> <option value="1997">1997</option> <option value="1998">1998</option> </select> <br><textarea id=result cols=60 rows=10 ></textarea>
你注意到傳入 Ajax.Request構(gòu)造方法的第二個對象了嗎? 參數(shù){method: 'get', parameters: pars, onComplete: showResponse} 表示一個匿名對象的真實寫法。他表示你傳入的這個對象有一個名為 method 值為 'get'的屬性,另一個屬性名為 parameters 包含HTTP請求的查詢字符串,和一個onComplete 屬性/方法包含函數(shù)showResponse。
還有一些其它的屬性可以在這個對象里面定義和設(shè)置,如 asynchronous,可以為true 或 false 來決定AJAX對服務(wù)器的調(diào)用是否是異步的(默認(rèn)值是 true)。
這個參數(shù)定義AJAX調(diào)用的選項。在我們的例子中,在第一個參數(shù)通過HTTP GET命令請求那個url,傳入了變量 pars包含的查詢字符串, Ajax.Request 對象在它完成接收響應(yīng)的時候?qū)⒄{(diào)用showResponse 方法。
也許你知道, XMLHttpRequest在HTTP請求期間將報告進度情況。這個進度被描述為四個不同階段:Loading, Loaded, Interactive, 或 Complete。你可以使 Ajax.Request 對象在任何階段調(diào)用自定義方法 ,Complete 是最常用的一個。想調(diào)用自定義的方法只需要簡單的在請求的選項參數(shù)中的名為 onXXXXX 屬性/方法中提供自定義的方法對象。 就像我們例子中的 onComplete 。你傳入的方法將會被用一個參數(shù)調(diào)用,這個參數(shù)是 XMLHttpRequest 對象自己。你將會用這個對象去得到返回的數(shù)據(jù)并且或許檢查包含有在這次調(diào)用中的HTTP結(jié)果代碼的 status 屬性。
還有另外兩個有用的選項用來處理結(jié)果。我們可以在onSuccess 選項處傳入一個方法,當(dāng)AJAX無誤的執(zhí)行完后調(diào)用, 相反的,也可以在onFailure選項處傳入一個方法,當(dāng)服務(wù)器端出現(xiàn)錯誤時調(diào)用。正如onXXXXX 選項傳入的方法一樣,這兩個在被調(diào)用的時候也傳入一個帶有AJAX請求的XMLHttpRequest對象。
我們的例子沒有用任何有趣的方式處理這個 XML響應(yīng), 我們只是把這段XML放進了一個文本域里面。對這個響應(yīng)的一個典型的應(yīng)用很可能就是找到其中的想要的信息,然后更新頁面中的某些元素, 或者甚至可能做某些XSLT轉(zhuǎn)換而在頁面中產(chǎn)生一些HTML。
在1.4.0版本中,一種新的事件回傳外理被引入。如果你有一段代碼總是要為一個特殊的事件執(zhí)行,而不管是哪個AJAX調(diào)用引發(fā)它,那么你可以使用新的Ajax.Responders對象。
假設(shè)你想要在一個AJAX調(diào)用正在運行時,顯示一些提示效果,像一個不斷轉(zhuǎn)動的圖標(biāo)之類的,你可以使用兩個全局事件Handler來做到,其中一個在第一個調(diào)用開始時顯示圖標(biāo),另一個在最后一個調(diào)用完成時隱藏圖標(biāo)??聪旅娴睦印?/P>
<script>
var myGlobalHandlers = {
onCreate: function(){
Element.show('systemWorking');
},
onComplete: function() {
if(Ajax.activeRequestCount == 0){
Element.hide('systemWorking');
}
}
};
Ajax.Responders.register(myGlobalHandlers);
</script>
<div id='systemWorking'><img src='spinner.gif'>Loading...</div>
更完全的解釋,請參照 Ajax.Request 參考 和 Ajax選項參考。
使用Ajax.Updater類
如果你的服務(wù)器的另一端返回的信息已經(jīng)是HTML了,那么使用這個程序包中 Ajax.Updater 類將使你的生活變得更加得容易。用它你只需提供哪一個元素需要被AJAX請求返回的HTML填充就可以了,例子比我寫說明的更清楚。
<script> function getHTML() { var url = 'http://yourserver/app/getSomeHTML'; var pars = 'someParameter=ABC';var myAjax = new Ajax.Updater( 'placeholder', url, { method: 'get', parameters: pars });} </script> <input type=button value=GetHtml onclick="getHTML()"> <div id="placeholder"></div>
你可以看到,這段代碼比前面的例子更加簡潔,不包括 onComplete 方法,但是在構(gòu)造方法中傳入了一個元素id。 我們來稍稍修改一下代碼來描述如何在客戶端處理服務(wù)器段錯誤成為可能。
我們將加入更多的選項, 指定處理錯誤的一個方法。這個是用 onFailure 選項來完成的。我們也指定了一個 placeholder 只有在成功請求之后才會被填充。為了完成這個目的我們修改了第一個參數(shù)從一個簡單的元素id到一個帶有兩個屬性的對象, success (一切OK的時候被用到) 和 failure (有地方出問題的時候被用到) 在下面的例子中沒有用到failure屬性,而僅僅在 onFailure 處使用了 reportError 方法。
<script>
function getHTML()
{
var url = 'http://yourserver/app/getSomeHTML';
var pars = 'someParameter=ABC';
var myAjax = new Ajax.Updater( {success: 'placeholder'}, url, { method: 'get', parameters: pars, onFailure: reportError });} function reportError(request) { alert('Sorry. There was an error.'); } </script> <input type=button value=GetHtml onclick="getHTML()"> <div id="placeholder"></div>
如果你的服務(wù)器邏輯是連同HTML 標(biāo)記返回JavaScript 代碼, Ajax.Updater對象可以執(zhí)行那段JavaScript代碼。為了使這個對象對待響應(yīng)為JavaScript,你只需在最后參數(shù)的對象構(gòu)造方法中簡單加入evalScripts: true屬性。但是值得提醒的是,像這個選項名evalScripts暗示的,這些腳本會被執(zhí)行,但是它們不會被加入到Page的腳本中?!坝惺裁磪^(qū)別?”,可能你會這樣問。我們假定請求地址返回的東東像這樣:
<script language="javascript" type="text/javascript"> function sayHi(){ alert('Hi'); } </script> <input type=button value="Click Me" onclick="sayHi()">
如果你以前這樣嘗試過,你知道這些腳本不會如你所期望的那樣工作,原因是這段腳本會被執(zhí)行,但像上面這樣的腳本執(zhí)行并不會創(chuàng)建一個名叫sayHi的函數(shù),它什么也不做。如果要創(chuàng)建一個函數(shù),我們應(yīng)當(dāng)把代碼改成下面這個樣子:
<script language="javascript" type="text/javascript">sayHi = function(){ alert('Hi'); };</script> <input type=button value="Click Me" onclick="sayHi()">
為什么我們在上面的代碼中不使用var關(guān)鍵字來聲明這個變量呢(指sayHi ),因為那樣做創(chuàng)建出來的函數(shù)將只是當(dāng)前腳本塊的一個局部變量(至少在IE中是這樣)。不寫var關(guān)鍵字,創(chuàng)建出來的對象的作用域就是我們所期望的window。
更多相關(guān)知識,請參看 Ajax.Updater reference 和options reference.
枚舉... 噢!噢!
你知道,我們都是這樣來做循環(huán)的,建一個Array,用elements組織它們,再建一個循環(huán)結(jié)構(gòu)(例如for,foreach,while)通過index數(shù)字來訪問每一個element,再用這個element做一些動作。
當(dāng)你想到這時,你會發(fā)現(xiàn)幾乎每次寫循環(huán)代碼你都會遲早用到一個Array。那么,如果Array對象能夠提供更多的功能給它們的迭代器使用不是很爽嗎?確實是這樣,事實上很多的編程語言都在它們的Array或其它類似的結(jié)構(gòu)中(如Collections,Lists)提供一些這樣的功能。
現(xiàn)在好了,prototype.js了給我們一個 Enumerable對象,它實現(xiàn)了很多和可迭代數(shù)據(jù)進行交互的竅門。和原有的JS對象相比prototype.js更上一層樓,它對Array 類s擴展了所有枚舉要用的函數(shù)。
循環(huán), Ruby樣式的
在標(biāo)準(zhǔn)的javascript中,如果你想把一個array中的所有elements顯示出來,你可以像下面代碼這樣寫得很好:
<script> function showList(){ var simpsons = ['Homer', 'Marge', 'Lisa', 'Bart', 'Meg'];for(i=0;i<simpsons.length;i++){ alert(simpsons[i]); }} </script> <input type="button" value="Show List" onclick="showList();" >
使用我們新的最好的朋友,prototype.js,我們可以把它生寫成這樣
function showList(){ var simpsons = ['Homer', 'Marge', 'Lisa', 'Bart', 'Meg'];simpsons.each( function(familyMember){ alert(familyMember); });}
你可能會想“非常奇怪的方式...相對舊的,這種語法太怪異了”。哦,在上面的例子,確實什么也沒有,在這個簡單得要死例子中,也沒有改變太多啊,盡管如此,請繼續(xù)讀下去。
在繼續(xù)下面內(nèi)容之前,你注意到那個被做為一個參數(shù)傳遞給each函數(shù)的函數(shù)?我們把它理解成迭代器函數(shù)。
Your arrays on steroids
就如我們上面提到的,把你的Array中的elements當(dāng)成相同的類型使用相同的屬性和函數(shù)是很通用(Common,不知該翻譯成通用還是庸俗)的。讓我們看看怎么樣利用我們新的馬力強勁的Arrays的迭代功能吧。
依照標(biāo)準(zhǔn)找到一個element。
<script> function findEmployeeById(emp_id){ var listBox = $('lstEmployees') var options = listBox.getElementsByTagName('option'); options = $A(options); var opt = options.find( function(employee){ return (employee.value == emp_id); }); alert(opt.innerHTML); //displays the employee name } </script> <select id="lstEmployees" size="10" > <option value="5">Buchanan, Steven</option> <option value="8">Callahan, Laura</option> <option value="1">Davolio, Nancy</option> </select> <input type="button" value="Find Laura" onclick="findEmployeeById(8);" >
現(xiàn)在我們再下一城,看看如何過濾一個Array中的元素,從每個元素中得到我們想要的成員。
<script> function showLocalLinks(paragraph){ paragraph = $(paragraph); var links = $A(paragraph.getElementsByTagName('a')); //find links that do not start with 'http' var localLinks = links.findAll( function(link){ var start = link.href.substring(0,4); return start !='http'; }); //now the link texts var texts = localLinks.pluck('innerHTML'); //get them in a single string var result = texts.inspect(); alert(result); } </script> <p id="someText"> This <a >text</a> has a <a href="#localAnchor">lot</a> of <a href="#otherAnchor">links</a>. Some are <a >external</a> and some are <a href="#someAnchor">local</a> </p> <input type=button value="Find Local Links" onclick="showLocalLinks('someText')">
上面的代碼僅僅是一點小小的實踐讓人愛上這種語法。請參看 Enumerable和Array的所有函數(shù)
prototype.js參考
JavaScript類擴展
prototype.js 類庫實現(xiàn)強大功能的一種途徑是擴展已有的JavaScript 類。
對 Object的擴展
Method | Kind | Arguments | Description |
---|---|---|---|
extend(destination, source) | destination: any object, source: any object | 提供一種通過拷貝所有源以象屬性和函數(shù)到目標(biāo)函數(shù)實現(xiàn)繼承的方法 | |
inspect(targetObj) | static | targetObj: any object | 返回可讀性好關(guān)于目標(biāo)對象的文字描述,如果對象實例沒有定義一個inspect函數(shù),默認(rèn)返回toString函數(shù)的值。 |
對Number的擴展
Method | Arguments | Description | |
---|---|---|---|
toColorPart() | (none) | 返回數(shù)字的十六進制表示形式。在把一個RGB數(shù)字轉(zhuǎn)換成HTML表現(xiàn)形式時很有用。 | |
succ() | instance | (none) | 返回下一個數(shù)字,這個方法可用于迭代調(diào)用場景中。 |
times(iterator) | instance | iterator: a function object conforming to Function(index) | Calls the iterator function repeatedly passing the current index in the index argument. 反復(fù)調(diào)用iterator函數(shù)并傳遞當(dāng)前index到iterator的index參數(shù)。 |
下面的例子用提示框顯示0-9。
<script> function demoTimes(){ var n = 10; n.times(function(index){ alert(index); }); /*************************** * you could have also used: * (10).times( .... ); ***************************/ } </script> <input type=button value="Test Number.times()" onclick="demoTimes()">
對 Function擴展
Method | Kind | Arguments | Description |
---|---|---|---|
bind(object) | object: the object that owns the method | 返回function的實例,這個實例和源function的結(jié)構(gòu)一樣,但是它已被綁定給了參數(shù)中提供的object,就是說,function中的this指針指向參數(shù)object。 | |
bindAsEventListener(object) | instance | object: the object that owns the method | 用法和上面的bind一樣,區(qū)別在于用來綁定事件。 |
讓我們看看如何運用這些擴展。
<input type=checkbox id=myChk value=1> Test? <script> //declaring the class var CheckboxWatcher = Class.create(); //defining the rest of the class implementation CheckboxWatcher.prototype = { initialize: function(chkBox, message) { this.chkBox = $(chkBox); this.message = message; //assigning our method to the eventthis.chkBox.onclick = this.showMessage.bindAsEventListener(this);}, showMessage: function(evt) { alert(this.message + ' (' + evt.type + ')'); } }; var watcher = new CheckboxWatcher('myChk', 'Changed'); </script>
對String的擴展
Method | Kind | Arguments | Description |
---|---|---|---|
stripTags() | instance | (none) | 返回一個把所有的HTML或XML標(biāo)記都移除的字符串。 |
stripScripts() | (none) | 返回一個把所有的script都移除的字符串。 | |
escapeHTML() | instance | (none) | 返回一個把所有的HTML標(biāo)記合適的轉(zhuǎn)義掉的字符串。 |
unescapeHTML() | instance | (none) | escapeHTML()的反轉(zhuǎn)。 |
extractScripts() | instance | (none) | 返回一個包含在string中找到的所有<script>的數(shù)組。 |
evalScripts() | instance | (none) | 執(zhí)行在string中找到的所有<script>。 |
toQueryParams() | instance | (none) | 把querystring分割才一個用parameter name做index的聯(lián)合Array,更像一個hash。 |
parseQuery() | instance | (none) | 和toQueryParams()一樣. |
toArray() | instance | (none) | 把字符串轉(zhuǎn)換成字符數(shù)組. |
camelize() | instance | (none) | 轉(zhuǎn)換一個以連字符連接的字符串成一個駱駝法樣式的字符串。比如,這個函數(shù)在寫代碼時,把它做為一個樣式工具使用是很有用的。 |
對 Array的擴展
因為array擴展于enumerable,所以所有enumberable對象的函數(shù),array都是可以使用的,除此之外,下面的這些也是已經(jīng)實現(xiàn)了的。
Method | Kind | Arguments | Description |
---|---|---|---|
clear() | (none) | 清空。 | |
compact() | instance | (none) | 返回一個不包括源array中null或undefined元素的array,此方法不改變源array。 |
first() | instance | (none) | 返回array的第一個對象。 |
flatten() | instance | (none) | 通過遞歸組合array每個元素的子元素(如果該元素也是array)來返回一個“扁平的”一維的array。 |
indexOf(value) | instance | value: what you are looking for. | 返回給出數(shù)字位置(從0算起)的元素,如果在該位置沒有找到對象,返回-1。 |
inspect() | instance | (none) | 重載inspect(),返回更好格式的反映Array每個元素的字符描述。 |
last() | instance | (none) | 返回最后一個元素。 |
reverse([applyToSelf]) | instance | applyToSelf: indicates if the array itself should also be reversed. | 反轉(zhuǎn)Array中元素的順序,如果沒有給出參數(shù),或參數(shù)為true,則源Array中元素的順序也反轉(zhuǎn),否則源Array保持不變。 |
shift() | instance | (none) | 返回Array的第一個元素并從Array中移除它,Array的Length-1。 |
without(value1 [, value2 [, .. valueN]]) | instance | value1 ... valueN: values to be excluded if present in the array. | 返回一個把參數(shù)列表中包含的元素從源Array中排除的Array。 |
document DOM擴展
Method | Kind | Arguments | Description |
---|---|---|---|
getElementsByClassName(className [, parentElement]) | className: name of a CSS class associated with the elements, parentElement: object or id of the element that contains the elements being retrieved. | 返回所有CSS className屬性等于className參數(shù)的元素,如果沒有給出parentElement,那么將搜索document body。(此處使用document.body我覺得不如使用document,因為有時有的頁面沒有body) |
Event擴展
Property | Type | Description |
---|---|---|
KEY_BACKSPACE | 8: Constant. Code for the Backspace key. | |
KEY_TAB | Number | 9: Constant. Code for the Tab key. |
KEY_RETURN | Number | 13: Constant. Code for the Return key. |
KEY_ESC | Number | 27: Constant. Code for the Esc key. |
KEY_LEFT | Number | 37: Constant. Code for the Left arrow key. |
KEY_UP | Number | 38: Constant. Code for the Up arrow key. |
KEY_RIGHT | Number | 39: Constant. Code for the Right arrow key. |
KEY_DOWN | Number | 40: Constant. Code for the Down arrow key. |
KEY_DELETE | Number | 46: Constant. Code for the Delete key. |
observers: | Array | List of cached observers. Part of the internal implementation details of the object. |
Method | Kind | Arguments | Description |
---|---|---|---|
element(event) | static | event: an Event object | 返回事件源對象。 |
isLeftClick(event) | static | event: an Event object | 如果點擊了鼠標(biāo)左鍵,返回true. |
pointerX(event) | static | event: an Event object | 返回鼠標(biāo)的X座標(biāo)。 |
pointerY(event) | static | event: an Event object | 返回鼠標(biāo)的Y座標(biāo)。 |
stop(event) | static | event: an Event object | 使用此函數(shù)來中斷事件的默認(rèn)行為并阻止傳遞(冒泡)。 |
findElement(event, tagName) | static | event: an Event object, tagName: name of the desired tag. | 從事件源對象開始向上搜索DOM樹,直到找到第一個符合tagName的元素 |
observe(element, name, observer, useCapture) | static | element: object or id, name: event name (like 'click', 'load', etc), observer: function to handle the event, useCapture: if true, handles the event in the capture phase and if false in the bubbling phase. | 為對象的某個事件增加一個處理函數(shù)。 |
stopObserving(element, name, observer, useCapture) | static | element: object or id, name: event name (like 'click'), observer: function that is handling the event, useCapture: if true handles the event in the capture phase and if false in the bubbling phase. | 和上面的函數(shù)相反。 |
_observeAndCache(element, name, observer, useCapture) | static | 私有函數(shù),別管它。 | |
unloadCache() | (none) | 私有函數(shù),別管它。從內(nèi)存中清除所有的observers緩存。 |
下面代碼演示如何給window添加一個load事件處理函數(shù)。
<script>
Event.observe(window, 'load', showMessage, false);
function showMessage() {
alert('Page loaded.');
}
</script>
在prototype.js中定義新的對象和類
另一個這個程序包幫助你的地方就是提供許多既支持面向?qū)ο笤O(shè)計理念又有共通功能的許多對象。
The PeriodicalExecuter object
這個對象提供一定間隔時間上重復(fù)調(diào)用一個方法的邏輯。
Method | Kind | Arguments | Description |
---|---|---|---|
[ctor](callback, interval) | callback: a parameterless function, interval: number of seconds | 創(chuàng)建這個對象的實例將會重復(fù)調(diào)用給定的方法。 |
Property | Type | Description |
---|---|---|
callback | 被調(diào)用的方法,該方法不能傳入?yún)?shù)。 | |
frequency | Number | 以秒為單位的間隔。 |
currentlyExecuting | Boolean | 表示這個方法是否正在執(zhí)行。 |
The Prototype object
Prototype 沒有太重要的作用,只是聲明了該程序包的版本 。
Property | Type | Description |
---|---|---|
Version | String | 版本。 |
emptyFunction | 空函數(shù)。 | |
K | Function(obj) | 一個僅僅回傳參數(shù)的函數(shù)。 |
ScriptFragment | String | 識別script的正則式。 |
The Enumerable object
Enumberable對象能夠已更優(yōu)雅的方式實現(xiàn)對列表樣式的結(jié)構(gòu)進行枚舉。
很多其它的對象通過擴展自Enumberable對象來得到這些有用的接口。
Method | Kind | Arguments | Description |
---|---|---|---|
each(iterator) | iterator: a function object conforming to Function(value, index) | 把每個element做為第一個參數(shù),element的index作為第一個參數(shù)調(diào)用iterator函數(shù)。 | |
all([iterator]) | instance | iterator: a function object conforming to Function(value, index) | 這個函數(shù)會用給出的iterator測試整個集合,如果集合中任一元素在iterator函數(shù)測試中返回false或null,那么這個函數(shù)返回false,否則返回true。如果沒有給出iterator,那么就會測試所有的元素是不是不等于false和null。你可以簡單的把它看成是“檢測每個元素都為非空非負(fù)”。 |
any(iterator) | instance | iterator: a function object conforming to Function(value, index), optional. | 這個函數(shù)會用給出的iterator測試整個集合,如果集合中任一元素在iterator函數(shù)測試中返回true,那么這個函數(shù)返回true,否則返回false。如果沒有給出iterator,那么就會測試所有的元素是不是有一個不等于false和null。你可以簡單的把它看成是“檢測元素中是不是有非空非負(fù)的”。 |
collect(iterator) | instance | iterator: a function object conforming to Function(value, index) | 調(diào)用iterator函數(shù)根據(jù)集合中每個元素返回一個結(jié)果,然后按照原來集合中的順序,返回一個Array。 |
detect(iterator) | instance | iterator: a function object conforming to Function(value, index) | 集合中每個元素調(diào)用一次Iterator,返回第一個使Iterator返回True的元素,如果最終都沒有為true的調(diào)用,那么返回null。 |
entries() | instance | (none) | 等于toArray(). |
find(iterator) | instance | iterator: a function object conforming to Function(value, index) | 等于 detect(). |
findAll(iterator) | instance | iterator: a function object conforming to Function(value, index) | 集合中每個元素調(diào)用Iterator,返回一個由所有調(diào)用Iterator返回結(jié)果等于true的元素組成的數(shù)組。和reject()相反。 |
grep(pattern [, iterator]) | instance | pattern: a RegExp object used to match the elements, iterator: a function object conforming to Function(value, index) | 用pattern參數(shù)正則表達(dá)式測試集合中的每個元素,返回一個包含所有匹配正則式的元素的Array,如果給出了Iterator,那個每個結(jié)果還要經(jīng)過一下Iterator處理。 |
include(obj) | instance | obj: any object | 判斷集合中包不包含指定對象。 |
inject(initialValue, iterator) | instance | initialValue: any object to be used as the initial value, iterator: a function object conforming to Function(accumulator, value, index) | 用Iterator聯(lián)接所有集合中的元素。Iterator在被調(diào)用時把上一次迭代的結(jié)果做為第一個參數(shù)傳給accumulator。第一次迭代時,accurmelator等于initialValue,最后返回accumulator的值。 |
invoke(methodName [, arg1 [, arg2 [...]]]) | instance | methodName: name of the method that will be called in each element, arg1..argN: arguments that will be passed in the method invocation. | 集合中的每個元素調(diào)用指定的函數(shù)(查看源代碼可以發(fā)現(xiàn)指定函數(shù)被調(diào)用時,this指針被傳成當(dāng)前元素),并傳入給出的參數(shù),返回調(diào)用結(jié)果組成的Array。 |
map(iterator) | instance | iterator: a function object conforming to Function(value, index) | 同collect(). |
max([iterator]) | instance | iterator: a function object conforming to Function(value, index) | 返回集合中元素的最大值,或調(diào)用Iterator后返回值的最大值(如果給出了Iterator的話)。 |
member(obj) | instance | obj: any object | 同 include(). |
min([iterator]) | instance | iterator: a function object conforming to Function(value, index) | 返回最小值,參見max()。 |
partition([iterator]) | instance | iterator: a function object conforming to Function(value, index) | 返回一個包含兩個Array的Array,第一個Array包含所有調(diào)用Iterator返回True的元素,第二個Array包含剩下的元素。如果Iterator沒有給出,那么就根據(jù)元素本身判斷。 |
pluck(propertyName) | instance | propertyName name of the property that will be read from each element. This can also contain the index of the element | 返回每個元素的指定屬性名的屬性的值組成的Array。 |
reject(iterator) | instance | iterator: a function object conforming to Function(value, index) | 和 findAll()相反(返回所有等于false的元素). |
select(iterator) | instance | iterator: a function object conforming to Function(value, index) | 同 findAll(). |
sortBy(iterator) | instance | iterator: a function object conforming to Function(value, index) | 根據(jù)每個元素調(diào)用Iterator返回的值進行排序返回一個Array。 |
toArray() | instance | (none) | 返回由集合所有元素組成的一個Array。 |
zip(collection1[, collection2 [, ... collectionN [,transform]]]) | instance | collection1 .. collectionN: enumerations that will be merged, transform: a function object conforming to Function(value, index) | 合并每個給出的集合到當(dāng)前集合。合并操作返回一個新的array,這個array的元素個數(shù)和原集合的元素個數(shù)一樣,這個array的每個元素又是一個子array,它合并了所有集合中相同index的元素。如果transform函數(shù)被指定,那么array的每個元素還會調(diào)用transform函數(shù)先做處理。舉個例子: [1,2,3].zip([4,5,6], [7,8,9]).inspect() 返回 "[ [1,4,7],[2,5,8],[3,6,9] ]" |
The Hash object
Hash對象實現(xiàn)一種Hash結(jié)構(gòu),也就是一個Key:Value對的集合。
Hash中的每個Item是一個有兩個元素的array,前一個是Key,后一個是Value,每個Item也有兩個不需加以說明的屬性,key和value。
Method | Kind | Arguments | Description |
---|---|---|---|
keys() | instance | (none) | 返回所有Item的key的集合的一個array。 |
values() | (none) | 返回所有Item的value的集合的一個array。 | |
merge(otherHash) | instance | otherHash: Hash object | 合并給出的Hash,返回一個新Hash。 |
toQueryString() | instance | (none) | 以QueryString那樣的樣式返回hash中所有的item,例如: 'key1=value1&key2=value2&key3=value3' |
inspect() | instance | (none) | 用一種合適的方法顯示hash中的key:value對。 |
The ObjectRange class
繼承自 Enumerable
用上、下邊界描述一個對象區(qū)域。
Property | Type | Kind | Description |
---|---|---|---|
start | (any) |
range的下邊界 | |
end | (any) | instance | range的上邊界 |
exclusive | Boolean | instance | 決定邊界自身是不是range的一部分。 |
Method | Kind | Arguments | Description |
---|---|---|---|
[ctor](start, end, exclusive) | constructor | start: the lower bound, end: the upper bound, exclusive: include the bounds in the range? | 創(chuàng)建一個range對象,從start生成到end,這里要注意的是,start和end必段類型一致,而且該類型要有succ()方法。 |
include(searchedValue) | searchedValue: value that we are looking for | 檢查一個value是不是在range中。 |
The Class object
在這個程序包中 Class 對象在聲明其他的類時候被用到 。用這個對象聲明類使得新類支持 initialize() 方法,他起構(gòu)造方法的作用。
看下面的例子
//declaring the class
var MySampleClass = Class.create();
//defining the rest of the class implmentation
MySampleClass.prototype = {
initialize: function(message) {
this.message = message;
},
showMessage: function(ajaxResponse) {
alert(this.message);
}
};
//now, let's instantiate and use one object
var myTalker = new MySampleClass('hi there.');
myTalker.showMessage(); //displays alert
Method | Kind | Arguments | Description |
---|---|---|---|
create(*) | (any) | 定義新類的構(gòu)造方法。 |
The Ajax object
這個對象被用作其他提供AJAX功能的類的根對象。
Property | Type | Kind | Description |
---|---|---|---|
activeRequestCount | Number | instance | 正在處理中的Ajax請求的個數(shù)。 |
Method | Kind | Arguments | Description |
---|---|---|---|
getTransport() | (none) | 返回新的XMLHttpRequest 對象。 |
The Ajax.Responders object
繼承自 Enumerable
這個對象維持一個在Ajax相關(guān)事件發(fā)生時將被調(diào)用的對象的列表。比如,你要設(shè)置一個全局鉤子來處理Ajax操作異常,那么你就可以使用這個對象。
Property | Type | Kind | Description |
---|---|---|---|
responders | Array | 被注冊到Ajax事件通知的對象列表。 |
Method | Kind | Arguments | Description |
---|---|---|---|
register(responderToAdd) | instance | responderToAdd: object with methods that will be called. | 被傳入?yún)?shù)的對象應(yīng)包含名如Ajax事件的系列方法(如onCreate,onComplete,onException)。通訊事件引發(fā)所有被注冊的對象的合適名稱的函數(shù)被調(diào)用。 |
unregister(responderToRemove) | instance | responderToRemove: object to be removed from the list. | 從列表中移除。 |
dispatch(callback, request, transport, json) | instance | callback: name of the AJAX event being reported, request: the Ajax.Request object responsible for the event, transport: the XMLHttpRequest object that carried (or is carrying) the AJAX call, json: the X-JSON header of the response (if present) | 遍歷被注冊的對象列表,找出有由callback參數(shù)決定的那個函數(shù)的對象。然后向這些函數(shù)傳遞其它的三個參數(shù),如果Ajax響應(yīng)中包含一個含有JSON內(nèi)容的X-JSON HTTP頭,那么它會被熱行并傳入json參數(shù)。如果事件是onException,那么transport參數(shù)會被異常代替,json不會傳遞。 |
The Ajax.Base class
這個類是其他在Ajax對象中定義的類的基類。
Method | Kind | Arguments | Description |
---|---|---|---|
setOptions(options) | options: AJAX options | 設(shè)定AJAX操作想要的選項。 | |
responseIsSuccess() | instance | (none) | 返回 true 如果AJAX操作成功,否則為 false 。 |
responseIsFailure() | instance | (none) | 與 responseIsSuccess() 相反。 |
The Ajax.Request class
繼承自 Ajax.Base
封裝 AJAX 操作
Property | Type | Kind | Description |
---|---|---|---|
Events | Array | static | 在AJAX操作中所有可能報告的事件/狀態(tài)的列表。這個列表包括: 'Uninitialized', 'Loading', 'Loaded', 'Interactive', 和 'Complete'。 |
transport | XMLHttpRequest | instance | 承載AJAX操作的 XMLHttpRequest 對象。 |
url | 請求的URL。 |
Method | Kind | Arguments | Description |
---|---|---|---|
[ctor](url, options) | constructor | url: the url to be fetched, options: AJAX options | 創(chuàng)建這個對象的一個實例,它將在給定的選項下請求url。onCreate事件在調(diào)用constructor事被激發(fā)。 重要: 如果選擇的url受到瀏覽器的安全設(shè)置,他會一點作用也不起。 很多情況下,瀏覽器不會請求與當(dāng)前頁面不同主機(域名)的url。 你最好只使用本地url來避免限制用戶配置他們的瀏覽器(謝謝Clay) |
evalJSON() | (none) | 這個方法顯然不會被外部調(diào)用。它在Ajax響應(yīng)中含有X-JSON HTTP頭時用于內(nèi)部調(diào)用執(zhí)行這些內(nèi)容。 | |
evalReponse() | instance | (none) | 這也方法顯然不會被外部調(diào)用,如果Ajax響應(yīng)含有一個值為text/javascript的Cotent-Type頭,那么這個方法就用被調(diào)用執(zhí)行響應(yīng)體。 |
header(name) | instance | name: HTTP header name | 引用Ajax響應(yīng)的頭的內(nèi)容,在Ajax訪問結(jié)束后再調(diào)用這個方法。 |
onStateChange() | instance | (none) | 這個方法通常不會被外部調(diào)用。 當(dāng)AJAX請求狀態(tài)改變的時候被這個對象自己調(diào)用。 |
request(url) | url: url for the AJAX call | 這個方法通常不會被外部調(diào)用。已經(jīng)在構(gòu)造方法中調(diào)用了。 | |
respondToReadyState(readyState) | instance | readyState: state number (1 to 4) | 這個方法通常不會被外部調(diào)用。 當(dāng)AJAX請求狀態(tài)改變的時候被這個對象自己調(diào)用。 |
setRequestHeaders() | instance | (none) | 這個方法通常不會被外部調(diào)用。 被這個對象自己調(diào)用來配置在HTTP請求要發(fā)送的HTTP報頭。 |
The options argument object
An important part of the AJAX operations is the options argument. There's no options class per se. Any object can be passed, as long as it has the expected properties. It is common to create anonymous objects just for the AJAX calls.
Property | Type | Default | Description |
---|---|---|---|
method | String | 'post' | HTTP 請求方式。 |
parameters | '' | 在HTTP請求中傳入的url格式的值列表。 | |
asynchronous | Boolean | true | 指定是否做異步 AJAX 請求。 |
postBody | String | undefined | 在HTTP POST的情況下,傳入請求體中的內(nèi)容。 |
requestHeaders | Array | undefined | 和請求一起被傳入的HTTP頭部列表, 這個列表必須含有偶數(shù)個項目, 任何奇數(shù)項目是自定義的頭部的名稱, 接下來的偶數(shù)項目使這個頭部項目的字符串值。 例子:['my-header1', 'this is the value', 'my-other-header', 'another value'] |
onXXXXXXXX | Function(XMLHttpRequest, Object) | undefined | 在AJAX請求中,當(dāng)相應(yīng)的事件/狀態(tài)形成的時候調(diào)用的自定義方法。 例如 var myOpts = {onComplete: showResponse, onLoaded: registerLoaded};. 這個方法將被傳入一個參數(shù), 這個參數(shù)是承載AJAX操作的 XMLHttpRequest 對象,另一個是包含被執(zhí)行X-JSON響應(yīng)HTTP頭。 |
onSuccess | Function(XMLHttpRequest, Object) | undefined | 當(dāng)AJAX請求成功完成的時候調(diào)用的自定義方法。 這個方法將被傳入一個參數(shù), 這個參數(shù)是承載AJAX操作的 XMLHttpRequest 對象,另一個是包含被執(zhí)行X-JSON響應(yīng)HTTP頭。 |
onFailure | Function(XMLHttpRequest, Object) | undefined | 當(dāng)AJAX請求完成但出現(xiàn)錯誤的時候調(diào)用的自定義方法。這個方法將被傳入一個參數(shù), 這個參數(shù)是承載AJAX操作的 XMLHttpRequest 對象,另一個是包含被執(zhí)行X-JSON響應(yīng)HTTP頭。 |
onException | Function(Ajax.Request, exception) | 當(dāng)一個在客戶端執(zhí)行的Ajax發(fā)生像無效響應(yīng)或無效參數(shù)這樣的異常情況時被調(diào)用的自定義函數(shù)。它收到兩個參數(shù),包含異常Ajax操作的Ajax.Request對象和異常對象。 | |
insertion | an Insertion class | undefined | 一個能決定怎么樣插入新內(nèi)容的類,能 Insertion.Before, Insertion.Top, Insertion.Bottom, 或 Insertion.After. 只能應(yīng)用于Ajax.Updater 對象. |
evalScripts | Boolean | undefined, false | 決定當(dāng)響應(yīng)到達(dá)的時候是否執(zhí)行其中的腳本塊,只在 Ajax.Updater 對象中應(yīng)用。 |
decay | Number | undefined, 1 | 決定當(dāng)最后一次響應(yīng)和前一次響應(yīng)相同時在 Ajax.PeriodicalUpdater 對象中的減漫訪問的次數(shù), 例如,如果設(shè)為2,后來的刷新和之前的結(jié)果一樣, 這個對象將等待2個設(shè)定的時間間隔進行下一次刷新, 如果又一次一樣, 那么將等待4次,等等。 不設(shè)定這個只,或者設(shè)置為1,將避免訪問頻率變慢。 |
frequency | Number | undefined, 2 | 用秒表示的刷新間的間隔,只能應(yīng)用于 Ajax.PeriodicalUpdater 對象。 |
The Ajax.Updater class
繼承自 Ajax.Request
當(dāng)請求的url返回一段HTML而你想把它直接放置到頁面中一個特定的元素的時候被用到。 如果url的返回<script> 的塊并且想在接收到時就執(zhí)行它的時候也可以使用該對象。含有腳本的時候使用 evalScripts 選項。
Property | Type | Kind | Description |
---|---|---|---|
containers | Object | instance | 這個對象包含兩個屬性:AJAX請求成功執(zhí)行的時候用到 containers.success , 否則的話用到 containers.failure 。 |
Method | Kind | Arguments | Description |
---|---|---|---|
[ctor](container, url, options) | constructor | container:this can be the id of an element, the element object itself, or an object with two properties - object.success element (or id) that will be used when the AJAX call succeeds, and object.failure element (or id) that will be used otherwise. url: the url to be fetched, options: AJAX options | 創(chuàng)建一個用給定的選項請求給定的url的一個實例。 |
updateContent() | (none) | 這個方法通常不會被外部調(diào)用。 當(dāng)響應(yīng)到達(dá)的時候,被這個對象自己調(diào)用。 它會用HTML更新適當(dāng)?shù)脑鼗蛘哒{(diào)用在 insertion 選項中傳入的方法-這個方法將被傳入兩個參數(shù), 被更新的元素和響應(yīng)文本。 |
The Ajax.PeriodicalUpdater class
這個類重復(fù)生成并使用 Ajax.Updater 對象來刷新頁面中的一個元素?;蛘邎?zhí)行 Ajax.Updater 可以執(zhí)行的其它任務(wù)。更多信息參照 Ajax.Updater 參考 。
Property | Type | Kind | Description |
---|---|---|---|
container | Object | 這個值將直接傳入Ajax.Updater的構(gòu)造方法。 | |
url | String | instance | 這個值將直接傳入Ajax.Updater的構(gòu)造方法。 |
frequency | Number | instance | 兩次刷新之間的間隔 (不是頻率) ,以秒為單位。 默認(rèn)2秒。 This 當(dāng)調(diào)用 Ajax.Updater 對象的時候,這個數(shù)將和當(dāng)前的 decay 相乘。 |
decay | instance | 重負(fù)執(zhí)行任務(wù)的時候保持的衰敗水平。 | |
updater | Ajax.Updater | instance | 最后一次使用的 Ajax.Updater 對象 |
timer | Object | instance | 通知對象該下一次更新時用到的JavaScript 計時器。 |
Method | Kind | Arguments | Description |
---|---|---|---|
[ctor](container, url, options) | constructor | container:this can be the id of an element, the element object itself, or an object with two properties - object.success element (or id) that will be used when the AJAX call succeeds, and object.failure element (or id) that will be used otherwise. url: the url to be fetched, options: AJAX options | 創(chuàng)建一個用給定的選項請求給定的url的一個實例。 |
start() | (none) | 這個方法通常不會被外部調(diào)用。 對象為了開始周期性執(zhí)行任務(wù)的時候調(diào)用的方法。 | |
stop() | instance | (none) | 使對象停止執(zhí)行周期任務(wù)。停止后,如果有onComplete選項,那么引發(fā)callback。 |
updateComplete() | instance | (none) | 這個方法通常不會被外部調(diào)用。 被當(dāng)前的 Ajax.Updater 使用,當(dāng)一次請求結(jié)束的時候,它被用作計劃下一次請求。 |
onTimerEvent() | instance | (none) | 這個方法通常不會被外部調(diào)用。當(dāng)?shù)较乱淮胃聲r被內(nèi)部調(diào)用。 |
The Element object
這個對象提供在操作DOM中元素時使用的功能性方法。
Method | Kind | Arguments | Description |
---|---|---|---|
addClassName(element, className) | instance | element: element object or id, className: name of a CSS class | 將給出的className添加到對象的className屬性中。 |
classNames(element) | element: element object or id | 返回一個Element.ClassName的對象表示CSS 給出對象有的class names。 | |
cleanWhitespace(element) | instance | element: element object or id | 清除對象子元素中所有空白的text node。 |
empty(element) | instance | element: element object or id | 返回一個布爾值指示對象為空或只有空白字符。 |
getDimensions(element) | instance | element: element object or id | 返回對象的尺寸,返回值有兩個屬性,height和width。 |
getHeight(element) | instance | element: element object or id | 返回元素的 offsetHeight 。 |
getStyle(element, cssProperty) | instance | element: element object or id, cssProperty name of a CSS property (either format 'prop-name' or 'propName' works). | 返回給定對象的CSS屬性值或沒有指定cssProperty時返回null。 |
hasClassName(element, className) | instance | element: element object or id, className: name of a CSS class | 返回 true 如果元素的類名中含有給定的類名 |
hide(elem1 [, elem2 [, elem3 [...]]]) | instance | elemN: element object or id | 通過設(shè)定style.display 為 'none'來隱藏每個傳入的元素。 |
makeClipping(element) | instance | element: element object or id | 能過設(shè)定overflow的值設(shè)定內(nèi)容溢出剪輯。 |
makePositioned(element) | instance | element: element object or id | 更改對象的style.position為'relative'。 |
remove(element) | instance | element: element object or id | 從document對象中刪除指定的元素。 |
removeClassName(element, className) | instance | element: element object or id, className: name of a CSS class | 從元素的類名中刪除給定的類名。 |
scrollTo(element) | instance | element: element object or id | 滾動window到對象的位置。 |
setStyle(element, cssPropertyHash) | instance | element: element object or id, cssPropertyHash Hash object with the styles to be applied. | 依照cssPropertyHash參數(shù)給對象設(shè)置CSS屬性值。 |
show(elem1 [, elem2 [, elem3 [...]]]) | instance | elemN: element object or id | 用設(shè)定它的 style.display 為 ''來顯示每個傳入的元素。 |
toggle(elem1 [, elem2 [, elem3 [...]]]) | instance | elemN: element object or id | 切換每一個傳入元素的可視性。 |
undoClipping(element) | instance | element: element object or id | style.overflow的值返回上一個設(shè)定值。 |
undoPositioned(element) | instance | element: element object or id | 清除對象的 style.position 為 '' |
update(element, html) | instance | element: element object or id, html: html content | 用給出的HTML參數(shù)替換對象的innerHTML,如果HTML參數(shù)中包含<script>,那么它們不會被包含進去,但是會執(zhí)行。 |
visible(element) | instance | element: element object or id | 返回一個布爾值指示對象可不可見。 |
The Element.ClassNames class
繼承自 Enumerable
在一個對象中表示CSS class names的集合。
Method | Kind | Arguments | Description |
---|---|---|---|
[ctor](element) | constructor | element: any DOM element object or id | 創(chuàng)建一個對象,給出對象的CSS class names被表現(xiàn)在這個ClassNames對象中。 |
add(className) | className: a CSS class name | 把CSS class name包含進對象的class names 列表。 | |
remove(className) | instance | className: a CSS class name | 從對象的class names列表中移除className |
set(className) | instance | className: a CSS class name | 設(shè)定對象CSS class name為className,移除其它class names。 |
The Abstract object
這個對象是這個程序包中其他類的根。它沒有任何屬性和方法。在這個對象中定義的類可以被視為傳統(tǒng)的抽象類。
The Abstract.Insertion class
這個類被用作其他提供動態(tài)內(nèi)容插入功能的類的基類,它像一個抽象類一樣被使用。
Method | Kind | Arguments | Description |
---|---|---|---|
[ctor](element, content) | constructor | element: element object or id, content: HTML to be inserted | 創(chuàng)建一個可以幫助插入動態(tài)內(nèi)容的對象。 |
contentFromAnonymousTable() | (none) | 對content通過匿名表格變成一個Node數(shù)組。 |
Property | Type | Kind | Description |
---|---|---|---|
adjacency | String | static, parameter | 這個參數(shù)指定相對于給定元素,內(nèi)容將被放置的位置。 可能的值是: 'beforeBegin', 'afterBegin', 'beforeEnd', 和 'afterEnd'. |
element | Object | instance | 與插入物做參照元素對象。 |
content | String | instance | 被插入的 HTML 。 |
The Insertion object
這個對象是其他類似功能的根。它沒有任何屬性和方法。在這個對象中定義的類仍然可以被視為傳統(tǒng)的抽象類。
The Insertion.Before class
在給定元素開始標(biāo)記的前面插入HTML。
Method | Kind | Arguments | Description |
---|---|---|---|
[ctor](element, content) | element: element object or id, content: HTML to be inserted | 繼承自 Abstract.Insertion. 創(chuàng)建一個可以幫助插入動態(tài)內(nèi)容的對象。 |
下面的代碼
<br>Hello, <span id="person" style="color:red;">Wiggum. How's it going?</span> <script> new Insertion.Before('person', 'Chief '); </script>
將把 HTML 變?yōu)?/P> <br>Hello, Chief <span id="person" style="color:red;">Wiggum. How's it going?</span>
The Insertion.Top class
在給定元素第一個子節(jié)點位置插入 HTML。內(nèi)容將位于元素的開始標(biāo)記的緊后面。
Method | Kind | Arguments | Description |
---|---|---|---|
[ctor](element, content) | element: element object or id, content: HTML to be inserted | 繼承自 Abstract.Insertion. 創(chuàng)建一個可以幫助插入動態(tài)內(nèi)容的對象。 |
下面的代碼
<br>Hello, <span id="person" style="color:red;">Wiggum. How's it going?</span> <script> new Insertion.Top('person', 'Mr. '); </script>
將把 HTML 變?yōu)?/P> <br>Hello, <span id="person" style="color:red;">Mr. Wiggum. How's it going?</span>
The Insertion.Bottom class
Inherits from Abstract.Insertion
在給定元素最后一個子節(jié)點位置插入 HTML。內(nèi)容將位于元素的結(jié)束標(biāo)記的緊前面。
Method | Kind | Arguments | Description |
---|---|---|---|
[ctor](element, content) | constructor | element: element object or id, content: HTML to be inserted | Inherited from Abstract.Insertion. Creates an object that will help with dynamic content insertion. |
The following code
<br>Hello, <span id="person" style="color:red;">Wiggum. How's it going?</span>
<script> new Insertion.Bottom('person', " What's up?"); </script>
Will change the HTML to
<br>Hello, <span id="person" style="color:red;">Wiggum. How's it going? What's up?</span>
The Insertion.After class
Inherits from Abstract.Insertion
在給定元素結(jié)束標(biāo)記的后面插入HTML。
Method | Kind | Arguments | Description |
---|---|---|---|
[ctor](element, content) | constructor | element: element object or id, content: HTML to be inserted | Inherited from Abstract.Insertion. Creates an object that will help with dynamic content insertion. |
The following code
<br>Hello, <span id="person" style="color:red;">Wiggum. How's it going?</span>
<script> new Insertion.After('person', ' Are you there?'); </script>
Will change the HTML to
<br>Hello, <span id="person" style="color:red;">Wiggum. How's it going?</span> Are you there?
The Field object
這個對象提供操作表單中的輸入項目的功能性方法。
Method | Kind | Arguments | Description |
---|---|---|---|
clear(field1 [, field2 [, field3 [...]]]) | instance | fieldN: field element object or id | 清除傳入表單中項目元素的值。 |
present(field1 [, field2 [, field3 [...]]]) | instance | fieldN: field element object or id | 只有在所有的表單項目都不為空時返回 true 。 |
focus(field) | field: field element object or id | 移動焦點到給定的表單項目。 | |
select(field) | instance | field: field element object or id | 選擇支持項目值選擇的表單項目的值。 |
activate(field) | instance | field: field element object or id | 移動焦點并且選擇支持項目值選擇的表單項目的值。 |
The Form object
這個對象提供操作表單和他們的輸入元素的功能性方法。
Method | Kind | Arguments | Description |
---|---|---|---|
serialize(form) | instance | form: form element object or id | 返回url參數(shù)格式的項目名和值的列表, 如'field1=value1&field2=value2&field3=value3'。 |
findFirstElement(form) | form: form element object or id | 返回Form中第一個Enable的對象。 | |
getElements(form) | instance | form: form element object or id | 返回包含所有在表單中輸入項目的 Array 對象。 |
getInputs(form [, typeName [, name]]) | instance | form: form element object or id, typeName: the type of the input element, name: the name of the input element. | 返回一個 Array 包含所有在表單中的 <input> 元素。 另外, 這個列表可以對元素的類型或名字屬性進行過濾。 |
disable(form) | instance | form: form element object or id | 使表單中的所有輸入項目無效。 |
enable(form) | instance | form: form element object or id | 使表單中的所有輸入項目有效。 |
focusFirstElement(form) | instance | form: form element object or id | 激活第一個表單中可視的,有效的輸入項目。 |
reset(form) | instance | form: form element object or id | 重置表單。和調(diào)用表單對象的 reset() 方法一樣。 |
The Form.Element object
這個對象提供表單對象中的可視和非可視元素的功能性方法。
Method | Kind | Arguments | Description |
---|---|---|---|
serialize(element) | element: element object or id | 返回元素的 名稱=值 對, 如 'elementName=elementValue'。 | |
getValue(element) | instance | element: element object or id | 返回元素的值。 |
The Form.Element.Serializers object
這個對象提供了內(nèi)部使用的用來協(xié)助解析出表單元素的當(dāng)前值的一些有用的方法。
Method | Kind | Arguments | Description |
---|---|---|---|
inputSelector(element) | instance | element: object or id of a form element that has the checked property, like a radio button or checkbox. | 返回帶有元素名稱和值的 Array , 如 ['elementName', 'elementValue'] |
textarea(element) | element: object or id of a form element that has the value property, like a textbox, button or password field. | 返回帶有元素名稱和值的 Array , 如 ['elementName', 'elementValue'] | |
select(element) | instance | element: object of a <select> element | 返回帶有元素名稱和所有被選擇的選項的值或文本的 Array , 如 ['elementName', 'selOpt1 selOpt4 selOpt9'] |
The Abstract.TimedObserver class
這個類是用于其它監(jiān)聽一個元素的值(或者任何類中涉及的屬性)變化的類的基類,這個類像一個抽象類一樣被使用。
子類可以被創(chuàng)建來監(jiān)聽如輸入項目值,或style屬性,或表格的行數(shù),或者其他任何對跟蹤變化相關(guān)的東西。
子類必須實現(xiàn)這個方法來決定什么才是被監(jiān)聽的元素的當(dāng)前值。
Method | Kind | Arguments | Description |
---|---|---|---|
[ctor](element, frequency, callback) | constructor | element: element object or id, frequency: interval in seconds, callback: function to be called when the element changes | 創(chuàng)建一個監(jiān)聽元素的對象。 |
getValue() | instance, abstract | (none) | 子類必須實現(xiàn)這個方法以瘊定什么這個元素被監(jiān)視的當(dāng)前值。 |
registerCallback() | (none) | 這個方法通常不會被外部調(diào)用。 被這個對象自己調(diào)用來開始監(jiān)聽那個元素。 | |
onTimerEvent() | instance | (none) | 這個方法通常不會被外部調(diào)用。 被這個對象自己調(diào)用來周期性的檢查那個元素。 |
Property | Type | Description |
---|---|---|
element | Object | 被監(jiān)聽的元素對象。 |
frequency | 每次檢查中的以秒為單位的時間間隔。 | |
callback | Function(Object, String) | 只要元素改變這個方法就會被調(diào)用。 會接收到元素對象和新值作為參數(shù)。 |
lastValue | String | 元素被核實的最后一個值。 |
The Form.Element.Observer class
Abstract.TimedObserver 的一個實現(xiàn)類用來監(jiān)聽表單輸入項目的值的變化。當(dāng)你想監(jiān)聽一個沒有帶報告值變化事件的元素的時候使用這個類。否則的話使用 Form.Element.EventObserver 類代替。
Method | Kind | Arguments | Description |
---|---|---|---|
[ctor](element, frequency, callback) | constructor | element: element object or id, frequency: interval in seconds, callback: function to be called when the element changes | 繼承自 Abstract.TimedObserver. 創(chuàng)建一個監(jiān)聽元素值屬性的對象。 |
getValue() | (none) | 返回元素的值。 |
The Form.Observer class
Abstract.TimedObserver 的一個實現(xiàn)類用來監(jiān)聽表單中任何數(shù)據(jù)項的值的變化。當(dāng)你想監(jiān)聽一個沒有帶報告值變化事件的元素的時候使用這個類。 否則的話使用類Form.EventObserver 代替。
Method | Kind | Arguments | Description |
---|---|---|---|
[ctor](form, frequency, callback) | constructor | form: form object or id, frequency: interval in seconds, callback function to be called when any data entry element in the form changes | 繼承自 Abstract.TimedObserver. 創(chuàng)建一個監(jiān)聽表單變化的對象。 |
getValue() | (none) | 返回所有表單數(shù)據(jù)的一系列值。 |
The Abstract.EventObserver class
這個類被用作其他一些類的基類,這些類具有在一個元素的值改變事件發(fā)生的時候執(zhí)行一個回調(diào)方法這樣的功能。
類 Abstract.EventObserver 的多個對象可以綁定到一個元素上,不是一個幫其他的擦出了,而是按照他們付給元素的順序執(zhí)行這些回調(diào)方法。
單選按鈕和復(fù)選框的觸發(fā)事件是 onclick ,而文本框和下拉列表框/下拉列表框的是 onchange 。
Method | Kind | Arguments | Description |
---|---|---|---|
[ctor](element, callback) | constructor | element: element object or id, callback: function to be called when the event happens | 創(chuàng)建監(jiān)聽元素的對象。 |
getValue() | (none) | 子類必須實現(xiàn)這個方法以瘊定什么這個元素被監(jiān)視的當(dāng)前值。 | |
registerCallback() | instance | (none) | 這個方法通常不會被外部調(diào)用。 被對象調(diào)用來把自己綁定到元素的事件上。 |
registerFormCallbacks() | instance | (none) | 這個方法通常不會被外部調(diào)用。 被對象調(diào)用來把自己綁定到表單中的每一個數(shù)據(jù)項元素的事件上。 |
onElementEvent() | instance | (none) | 這個方法通常不會被外部調(diào)用。 將被綁定到元素的事件上。 |
Property | Type | Description |
---|---|---|
element | Object | 被監(jiān)聽的元素對象。 |
callback | Function(Object, String) | 只要元素改變就調(diào)用的方法。會接收到元素對象和新值作為參數(shù)。 |
lastValue | String | 元素被核實的最后一個值。 |
The Form.Element.EventObserver class
Abstract.EventObserver 的一個實現(xiàn)類,它在監(jiān)測到表單中數(shù)據(jù)項元素的值改變的相應(yīng)事件時候執(zhí)行一個回調(diào)方法。 如果元素沒有任何報告變化的事件,那么你可以使用 Form.Element.Observer 類代替。
Method | Kind | Arguments | Description |
---|---|---|---|
[ctor](element, callback) | constructor | element: element object or id, callback: function to be called when the event happens | 繼承自 Abstract.EventObserver。 創(chuàng)建一個監(jiān)聽元素值屬性的對象。 |
getValue() | (none) | 返回元素的值。 |
The Form.EventObserver class
Abstract.EventObserver 的一個實現(xiàn)類,監(jiān)聽表單對象中包含的任何對象的任何變化,用元素的事件檢測值的變化。如果元素沒有任何報告變化的事件, 那么你可以使用Form.Observer 類代替。
Method | Kind | Arguments | Description |
---|---|---|---|
[ctor](form, callback) | constructor | form: form object or id, callback: function to be called when any data entry element in the form changes | 繼承自 Abstract.EventObserver。 創(chuàng)建一個監(jiān)聽元素值屬性的對象。 |
getValue() | (none) | 返回所有表單數(shù)據(jù)的一系列值。 |
Position 對象 (預(yù)備文檔)
這個對象提供許多和元素位置相關(guān)的方法。
Method | Kind | Arguments | Description |
---|---|---|---|
prepare() | (none) | 調(diào)整 deltaX 和 deltaY 屬性來協(xié)調(diào)在滾動位置中的變化。 記得在頁面滾動之后的任何調(diào)用的withinIncludingScrolloffset 之前調(diào)用這個方法。 | |
realOffset(element) | element: object | 返回這個元素的正確滾動偏差的 Array 對象, 包括所有影響元素的滾動偏差。結(jié)果數(shù)組類似 [total_scroll_left, total_scroll_top] | |
cumulativeOffset(element) | instance | element: object | 回這個元素的正確滾動偏差的 Array 對象, 包含任何被放置的父元素強加偏差。結(jié)果數(shù)組類似 [total_offset_left, total_offset_top] |
within(element, x, y) | instance | element: object, x and y: coordinates of a point | 測試給定的點的坐標(biāo)是否在給定的元素的外部矩形范圍之內(nèi)。 |
withinIncludingScrolloffsets(element, x, y) | instance | element: object, x and y: coordinates of a point | 測試給定的點的坐標(biāo)是否在給定的元素的外部矩形范圍之內(nèi)(包含scroll offsets)。 |
overlap(mode, element) | mode: 'vertical' or 'horizontal', element: object | 在調(diào)用這個方法之前需要調(diào)用within() 。這個方法返回0.0到1.0之間的數(shù)字,來表示坐標(biāo)在元素重疊的分?jǐn)?shù)。 舉個例子,如果元素是一個邊長是100px的正方形的DIV,并且位于(300, 300), 然后 within(divSquare, 330, 330);overlap('vertical', divSquare); 會返回 0.10,意思是那個點位于DIV頂部邊框以下 10% (30px) 的位置上。 | |
clone(source, target) | instance | source: element object or id, target: element object or id | 改變目標(biāo)元素的大小尺寸和位置與源元素的相同。 |
相關(guān)文章
Prototype PeriodicalExecuter對象 學(xué)習(xí)
這個對象就是可以周期性的執(zhí)行某個方法,但是在它內(nèi)部維持了一個狀態(tài),可以防止由于某些原因一次調(diào)用沒執(zhí)行,然后下一次調(diào)用又來了,這樣會造成連續(xù)執(zhí)行兩次方法。上面的第二斷英文就是這個意思。2009-07-07滾動經(jīng)典最新話題[prototype框架]下編寫
滾動經(jīng)典最新話題[prototype框架]下編寫...2006-10-10不錯的一篇關(guān)于javascript-prototype繼承
不錯的一篇關(guān)于javascript-prototype繼承...2007-08-08Prototype 學(xué)習(xí) 工具函數(shù)學(xué)習(xí)($w,$F方法)
Prototype $w $F使用方法2009-07-07prototype Element學(xué)習(xí)筆記(Element篇三)
上一篇把Element的所函數(shù)都梳理了一遍,下面總結(jié)一下這些函數(shù)的功能,畢竟函數(shù)太多,不分門別類一下還是沒有底。2008-10-10Prototype源碼淺析 String部分(一)之有關(guān)indexOf優(yōu)化
Prototype源碼淺析 String部分(一)之有關(guān)indexOf優(yōu)化介紹,需要的朋友可以參考下。2012-01-01