{jQuery心得} - each
首先,這是一個
p { margin: 4px; font-size:16px; font-weight:bolder;
cursor:pointer; }
.blue { color:blue; }
.highlight { background:red; }
Script<p class="blue">Click to toggle (<span>clicks: 0</span>)</p> <p class="blue highlight">highlight (<span>clicks: 0</span>)</p> <p class="blue">on these (<span>clicks: 0</span>)</p> <p class="blue">paragraphs (<span>clicks: 0</span>)</p>
在這樣的狀況下,設定點擊即會增加後面的數字
///////////////////////////////
Script
script
var count = 0;
$('p').click(function(){
count++;
$(this).find('span').text('clicks: ' + count);
$(this).toggleClass("highlight", count % 3 == 0);
})
可是,count只有一個,那麼當每個都當時,卻是全部的累加
(以下是每個p都點一下的結果)
///////////////////////////////
Script使用了each
var count = 0;
$("p").each(function() {
var $thisParagraph = $(this);
var count = 0;
$thisParagraph.click(function() {
count++;
$thisParagraph.find("span").text('clicks: ' + count);
$thisParagraph.toggleClass("highlight", count % 3 == 0);
});
});
在此可以發現,
在each之中,每個都有一個count
留言
張貼留言