2012-02-28 58 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) 
    }) 
}