2012-02-28 53 views
0

以及我還是新來的js /編程。 可以以任何方式指導我如何優化我的代碼? 我相信有很多方法可以編寫一個小而快的代碼來完成同樣的事情。jquery快捷鍵多次點擊

$('.ourservices-content .left ul li:nth-child(1)').click(function(){ 
     $('.our-services-content-box > ul.box').stop().animate({ 
      marginLeft: '0px' 
     },800) 
    }) 

    $('.ourservices-content .left ul li:nth-child(2)').click(function(){ 
     $('.our-services-content-box > ul.box').stop().animate({ 
      marginLeft: '-600px' 
     },800) 
    }) 

    $('.ourservices-content .left ul li:nth-child(3)').click(function(){ 
     $('.our-services-content-box > ul.box').stop().animate({ 
      marginLeft: '-1200px' 
     },800) 
    }) 

    $('.ourservices-content .left ul li:nth-child(4)').click(function(){ 
     $('.our-services-content-box > ul.box').stop().animate({ 
      marginLeft: '-1800px' 
     },800) 
    }) 

    $('.ourservices-content .left ul li:nth-child(5)').click(function(){ 
     $('.our-services-content-box > ul.box').stop().animate({ 
      marginLeft: '-2400px' 
     },800) 
    }) 

    $('.ourservices-content .left ul li:nth-child(6)').click(function(){ 
     $('.our-services-content-box > ul.box').stop().animate({ 
      marginLeft: '-3000px' 
     },800) 
    }) 

    $('.ourservices-content .left ul li:nth-child(7)').click(function(){ 
     $('.our-services-content-box > ul.box').stop().animate({ 
      marginLeft: '-3600px' 
     },800) 
    }) 

回答

2

這應做到:

$('.ourservices-content .left ul li').each(function (index) { 
    $(this).click(function() { 
     $('.our-services-content-box > ul.box').stop().animate({ 
      marginLeft: '-' + (600 * index) + 'px'; 
     }, 800); 
    }); 
}); 

我們正在做的是通過選擇在原$()呼叫匹配的每個元素循環。然後,對於每個匹配的元素,我們調整動畫參數marginLeft,從第零個元素開始,通過哪個元素索引進行調整。

+0

另外,如果你能,增加一個ID爲第一選擇,所以這只是'「#ulId禮」 '甚至''#ulId> li「'會是一個更有效的選擇器。 – 2012-02-28 05:45:23

+0

很好地去除';'在「動畫... +'px'」之後 – max 2012-02-28 05:52:24

+0

您可以......但是有些人認爲最好不要依賴Javascript的分號插入。道格拉斯克羅克福德非常有見地,衷心推薦它。這可能是做這件事的原因......或不這樣做。由你決定。 – 2012-02-28 05:59:45

0

有我能想到的一些方法,但最簡單的將它包裝在一個function,在array排隊你的數據了,然後調用functionfor循環:

function animate_box(count,margin) { 
    $('.ourservices-content .left ul li:nth-child('+count+')').click(function(){ 
     $('.our-services-content-box > ul.box').stop().animate({ 
      marginLeft: margin+'px' 
     },800) 
    }) 
} 
var left_margin=0; 
var indexes=[1,2,3,4,2,2]; 
for(var i=0;i<indexes.length;i++) { 
    animate_box(indexes[i],left_margin); 
    left_margin-=600; 
} 
0

我沒有辦法去嘗試這一點,但這樣的事情是觀念...

var $items = $('.ourservices-content .left li'); 
for (var i = 0, len = $items.length; i < len; i++) { 
    $items.eq(i).click(function() { 
     $('.box').stop().animate({ 
      marginLeft : '-=600'; 
     }, 800) 
    }) 
}