2013-03-29 93 views
0

請注意,我不是jQuery大師,只是還在學習。jQuery:在選擇器內使用變量

我有這個looong功能:

$('.client1 > *:first-of-type, .client2 > *:first-of-type, .client3 > *:first-of-type, .client4 > *:first-of-type, .client5 > *:first-of-type').append('<span class="jsi"/>');

它的工作,是的,但我知道這是效率不高,不容易擴展,因爲每次我需要添加一個新的「客戶」我要將其添加到選擇器列表中。

所以我知道我可以使用(a)變量作爲> *:first-of-type的一部分,也可以是.clientX部分的「數組」(我不知道我是否說得對)。

這確實有點凌駕於我的頭上。

這是我做過嘗試,但當然不工作:

var fot = "> *:first-of-type"; 
$('.client1' + fot, '.client2' + fot, '.client3' + fot, '.client4' + fot, '.client5' + fot).append('<span class="jsi"/>'); 

會發生什麼事,不僅是我想不必重複自己,但能更有效地擴展這個新客戶端需要添加到該功能。

對此非常感謝。

+1

給出一個通用的'client'類而不是'client1'和'client2',例如'

'那麼你的查詢很簡單:'$('。client> *:first-of-type')' –

+0

同意Eli,Sven的答案讓我意識到這一點。給你一個upvote。謝謝。 –

回答

3

只需添加額外的課程,例如client,並且您不再需要所有這些東西。

<div class="client client1">..</div> 
<div class="client client2">..</div> 

因此,您可以選擇類別爲client的所有元素。

$('.client > *:first-of-type').each(function() { 
    $(this).append('<span class="jsi" />'); 
}); 
+0

哦,男孩,我看到Sven ......我被固定在'clientX'部分,所以我沒有看到你的建議。非常感謝! –