2010-09-28 27 views
0

我一直在努力學習如何編寫更快更高效的jQuery,並想了解我應該如何編寫這個函數,以便它能更快地工作。我應該使用變量,我最關心的是頁面上的速度,所以什麼會運行更優化的跨瀏覽器,爲什麼是我想看到的答案。什麼是更高效/優化的寫這個函數的方式

$("#div-one, #div-two").find('tr').hover(function(){ 
    $(this).find('a').stop().animate({color:"#FFF"}, 'fast'); 
    $(this).stop().animate({ 
     backgroundColor:"#7DBE36" 
    }, 'fast'); 
}, function(){ 
    $(this).find('a').stop().animate({color:"#000"}, 'fast'); 
    $(this).stop().animate({ 
     backgroundColor:"#FFF" 
    }, 'fast') 
}); 

非常感謝。

回答

2

你可以在這裏使用.delegate(),像這樣:

$("#div-one, #div-two").delegate('tr', 'mouseenter', function(){ 
    $(this).stop().animate({ backgroundColor:"#7DBE36" }, 'fast') 
      .find('a').stop().animate({ color:"#FFF" }, 'fast'); 
}).delegate('tr', 'mouseleave', function(){ 
    $(this).stop().animate({ backgroundColor:"#FFF" }, 'fast') 
      .find('a').stop().animate({ color:"#000" }, 'fast'); 
}); 

這個高度上#div-one一對處理器和#div-two而不是每個<tr>內各對,這意味着更快的約束力,只是依賴於事件冒着聆聽事件的冒險精神。也可以鏈接功能,不需要另外創建一個$(this) jQuery對象。

+0

這正是我正在尋找的,謝謝。 Unfortunatley我正在使用Drupal需要的jQuery的老版本V,但這是我將來需要的東西。謝謝! – jeffreynolte 2010-09-28 20:56:56

0

你可以寫另一個實用功能,讓您切換回調:

function animCallback(linkColor, bgColor) { 
    return function() { 
    $(this).stop().animate({backgroundColor: bgColor}, 'fast') 
     .find('a').stop().animate({color: linkColor}, 'fast'); 
    }; 
} 
$('#div-one, #div-two').find('tr').hover(
    animCallback('#FFF', '#7DBE36'), 
    animCallback('#000', '#FFF') 
); 

編輯還尼克的想法是好的 - 你可以結合這兩個我們的答案!

+0

感謝您的回答,尼克斯是我一直在尋找的,但仍然有價值。 – jeffreynolte 2010-09-28 20:58:58

0

除了按照Nick的建議使用delegate之外,您還可以重新使用$(this)的結果進行額外的微觀優化。

$("#div-one, #div-two").delegate('tr', 'mouseenter', function(){ 
    var $this = $(this); 
    $this.find('a').stop().animate({color:"#FFF"}, 'fast'); 
    $this.stop().animate({ backgroundColor:"#7DBE36" }, 'fast'); 
}).delegate('tr', 'mouseleave', function(){ 
    var $this = $(this); 
    $this.find('a').stop().animate({color:"#000"}, 'fast'); 
    $this.stop().animate({ backgroundColor:"#FFF" }, 'fast'); 
}); 

編輯尼克改變了他的答案,使用鏈接從而避免在首位的$(this)重用。所以我會選擇他的版本。

0

作爲一名jQuery開發人員,我有一個簡單的規則,如果我將在一個作用域中多次使用一個選擇器,我將它存儲在一個變量中。

$("#div-one tr, #div-two tr").hover(function() { 
    var $this = $(this); 
    $this.find('a').stop().animate({color:"#FFF"}, 'fast'); 
    $this.stop().animate({backgroundColor:"#7DBE36"}, 'fast'); 
}, function(){ 
    var $this = $(this); 
    $this.find('a').stop().animate({color:"#000"}, 'fast'); 
    $this.stop().animate({backgroundColor:"#FFF"}, 'fast'); 
}); 

我聽到或讀到的jQuery使用$(...)爲相同或選擇對象時使用某種緩存。 jQuery本身用於包裝關鍵字this並將其存儲在本地變量中。

簡而言之,要優化jQuery代碼,您應避免使用$(...)作爲函數範圍中的相同選擇器。提高性能的更好的做法是使用它一次並存儲在一個變量中。

編輯

尖尖尼克Craver閱讀答案後,它不會是必要的這種優化你的代碼。因爲在兩個答案中,他們都使用$(this)一次。

PD感謝您的評論/反饋!

+0

謝謝,這是我一定會使用的經驗法則。 – jeffreynolte 2010-09-28 20:59:23

相關問題