2013-03-28 23 views
1

這就是我所擁有的,它的工作原理,但我不知道它是否會更容易?重複功能只是改變一個變種

$('.item1').click(function(){ 
    $('.otheritem').animtate('left':'0'); 
}); 
$('.item2').click(function(){ 
    $('.otheritem').animtate('left':'100'); 
}); 
$('.item3').click(function(){ 
    $('.otheritem').animtate('left':'200'); 
}); 
// etc etc etc 

我有一個文件,使用PHP foreach並生成一些項目。在更多的項目

foreach($images as $image) 
{ 
    $i++; 
    echo "<a class='item$i item' href='#'>$i</a>"; 
} 

所以更多的圖像,所以如果你點擊在PHP中生成的項目之一,將決定.otheritem的位置

回答

2

你可以嵌入件上的數據屬性內的變化值,只是把所有的元素相同的選擇 -

$animLeft = $i * 100; 
echo "<a class='item' href='#' data-animleft='{$animLeft}' >$i</a>"; 

現在你的jQuery可通過同一接入的所有元素名稱和動畫中提取值:

$('.item').on('click',function(){ 
    var animateValue = $(this).data('animleft'); 
    $('.otheritem').animtate('left':animateValue); 
}); 

參考 -

+0

+1'數據':d – Chad

+0

感謝@chad:P這也是我的第1000個答案! ** WOO HOO!** – Lix

+0

不錯!恭喜! – Chad

2

如果所有的項目都是固定的寬度,就可以計算出該位置基於它在列表中的位置。

例如

$('.buttons').click(function() { 
    $('.otheritem').animate('left', $(this).index() * 100); 
}); 
1

是這樣的?

$('.item').each(function(i) { 
    $(this).click(function() { 
     $('.otheritem').animate('left', i * 100); 
    }); 
});