2012-12-08 35 views
2

我想了解如何使用jquery的each(),因爲我到目前爲止所嘗試的都不起作用。在這個簡單的例子中使用each()不起作用

在我的示例中,我嘗試使用.each()爲任何'特殊'div單擊時向第一個元素添加邊框。下一次單擊「特殊」div時,請在第二個'特殊'元素上添加邊框。第三時間任何 '特殊' 的div被點擊添加邊框到第三個元素,等等

JS

$.each(function(i) { 
    $('.special').click(function(){ 
     $('.special[i]').css('border','2px solid red'); 
    } 
    i++; 
}); 

HTML

<div class="special">fooft1</div> 
    <div class="special">fooft2</div> 
    <div class="special">fooft3</div> 
    <div class="special">fooft4</div> 
    <div class="special">fooft5</div> 
    <div class="special">fooft6</div> 
+0

無需'。每()'這裏 – VIDesignz

+0

感謝您的答覆,爲什麼每個()不恰當的嗎? – AnchovyLegend

+0

將'.click'附加到類'.special'it時,它會自動將它附加到具有'.special'類的所有元素** – VIDesignz

回答

1
var i = 0; 
$('.special').click(function(){ 
     $(".special:eq("+i+")").css('border','2px solid red'); 
    } 
    i++; 
}); 
+0

感謝您的回覆。你能看到編輯後,我無法成功地將這個邏輯應用到我的代碼。 – AnchovyLegend

1

你不想each爲這個:

(function() { 
    var nextIndex = 0; 

    $(".special").click(function() { 
     $('.special').eq(nextIndex).css('border','2px solid red'); 
     ++nextIndex; 
    }); 

})(); 

(換行功能的原因是我不想讓nextIndex成爲全球性的。如果你的代碼是已經函數裏面,你不需要額外的包裝)

或者如果特價不是動態的,你可以調用之間記住他們,如果你想:

(function() { 
    var nextIndex = 0, 
     specials = $(".special"); 

    specials.click(function() { 
     specials.eq(nextIndex).css('border','2px solid red'); 
     ++nextIndex; 
    }); 

})(); 

如果您經過最後一個行爲,例如移除處理程序或類似行爲,您可能還需要一些行爲。

+0

感謝您的答覆。你能看到編輯後,我無法將這個邏輯應用於我的代碼:/ – AnchovyLegend

1

試試這個

var i = 0; 
$('.special').click(function() { 
    $('.special').eq(i).css('border', '2px solid red'); 
    i++; 
}); 

工作FIDDLE

+0

感謝您的答覆。這適用於邊界,但是,你可以請參閱編輯的帖子,我無法將這個邏輯應用於我的代碼。 – AnchovyLegend

1

.each()是一個迭代函數。作爲for each聲明的替代品,它是有用的。

此外,您的第二個選擇器不正確'.special[i]'這不會被jQuery解釋。爲了使它工作,你必須連接變量'.special[' + i + ']'。這將使您的代碼將邊框添加到集合中的每個元素。

0
$('div.special').each(function(i,e) { 
    $(this).click(function() { 
     if($(this).hasClass('current')) { 
      $(this).css('border', '1px solid red').removeClass('current'); 
      $(this).next().addClass('current'); 
     } 
    });   
}); 

<div class="special current">fooft1</div> 
<div class="special">fooft2</div> 
<div class="special">fooft3</div> 
<div class="special">fooft4</div> 
<div class="special">fooft5</div> 
<div class="special">fooft6</div> 

http://jsfiddle.net/v7gJF/

+0

感謝您的回覆。不完全是我需要的。單擊任何特殊格來添加邊框時不起作用。 – AnchovyLegend

+0

我更新了HTML,當頁面加載時,你應該在第一個div的類當前;) – shaddy

+0

仍然不能正常工作哈哈:)你是jquery應該添加邊框到下一個'特殊'元素,每次任何特殊元素是點擊,它沒有。 – AnchovyLegend

相關問題