jQuery使用得比較順手也比較喜歡,不得已也要用Prototype,小小整理下區別。。
頁面載入
-
// JQuery
- $ ( document ). ready ( function () {
- // Code
- });
-
// JQuery Shorthand
- $ ( function () {
- // Code
- });
-
// Prototype
- document . observe ( 'dom:loaded' , function () {
- // Code
- });
根據ID獲取
-
// JQuery
- $ ( "#idname" );
-
// Prototype
- $ ( "idname" );
根據類名
-
// JQuery
- $ ( ".classname" );
-
// Prototype
- $$ ( '.classname' );
根據第一個符合的類名
-
// JQuery
- $ ( ".classname:first-child" );
-
// Prototype
- $$ ( '.classname' )[ 0 ];
根據ID綁定監聽事件
-
// JQuery
- $ ( "#item" ). bind ( 'click' , function () {
- // Code
- });
- // JQuery Shorthand
- $ ( "#item" ). click ( function () {
- // Code
- });
-
// Prototype
- $ ( "#item" ). observe ( 'click' , function () {
- // code
- });
根據符合的類名綁定監聽事件
-
$(".classname").bind('click',function(){
- // code
- });
- // JQuery Shorthand
- $ ( ".classname" ). click ( function () {
- // code
- });
-
// Prototype
- $$ ( ".classname" ). invoke ( 'observe' , 'click' , function () {
- // code
- });
結束終止事件
-
// JQuery
- $ ( "#id" ). click ( function () {
- //code
- return false ;
- });
-
// Prototype
- $ ( "id" ). observe ( 'click' , function ( e ) {
- //code
- Event . stop ( e );
- });
處理觀察的元素
-
// JQuery
- $ ( '#idname' ). click ( function () {
- this . hide (); // Hide the item clicked
- });
-
// Prototype
- $ ( 'idname' ). observe ( 'click' , function ( e ) {
- el = e . findElement ;
- el . hide (); // hide the item clicked
- });
根據ID操作類名
-
// JQuery
- $ ( '#id' ). addClass ( 'red' );
- $ ( '#id' ). removeClass ( 'red' );
-
// Prototype
- $ ( 'id' ). addClassName ( 'red' );
- $ ( 'id' ). removeClassName ( 'red' );
根據類名操作類名。。
-
// JQuery
- $ ( '.class' ). addClass ( 'red' );
- $ ( '.class' ). removeClass ( 'red' );
-
// Prototype
- $$ ( '.class' ). invoke ( 'addClassName' , 'red' );
- $$ ( '.class' ). invoke ( 'removeClassName' , 'red' );
AJAX請求和JSON應用
-
$.get(url,function(data){ alert(data . name );
- }, 'JSON' );
-
// Prototype new Ajax . Request ( url , {
- method : 'get' ,
- onSuccess : function ( transport , json ) {
- alert ( json . name );
- }
- });
可以得出結論:jQuery和Prototype大部分是極爲相似的,多用幾次就都熟了。。