2011-08-01 94 views
1

的我是新來的,無法找到任何類似的答案,我想要的東西;我取得了進展,不能再走下去。下面是我的剪輯,當我在第二個到第二個TR之間徘徊時,它會改變顏色。 (第一個TR是標題,最後一個TR是頁腳)。在懸停範圍之間,我如何選擇它只包括第二個TD和第二個最後一個TD。jQuery的懸停範圍TD

$('table#tblSchoolList tr:gt(0)').hover(function(){ 
    ////and not the last child (.next length = 0 means last) 
    if ($(this).next().length != 0){ 
     $(this).css("background", "red"); 
    } 
}, function(){ 
    $(this).css("background", ""); 
}) 

總之,表懸停排除第一個和最後TR和TD。

TIA。

+1

你的意思是隻改變顏色當你懸停行時,每行的第二和第二個單元格? – BoltClock

+0

上面的代碼爲我描述了需求(突出顯示了第一個和最後一個之間的所有trs) - 請參閱http://jsfiddle.net/cK8Q5/1/ –

+0

是BoltClock。肯雷德勒剛剛改善了tr範圍選擇,但並沒有解決我的問題。細胞的數量是動態的,概念與tr相同,只是不是第一個和最後一個細胞。 – Gian

回答

2

您可以使用.find()和以下選擇器排除每個tr的第一個和最後一個td s:

$('table#tblSchoolList tr:gt(0)').hover(function() { 
    if ($(this).next().length != 0) { 
     $(this).find('td:not(:first-child, :last-child)').css("background", "red"); 
    } 
}, function() { 
    $(this).find('td:not(:first-child, :last-child)').css("background", ""); 
}); 

功能依舊會觸發如果鼠標是在第一和最後一個td S,但他們不會顏色。

jsFiddle demo

您也可以與您的tr的使用選擇,避免需要if語句:

$('table#tblSchoolList tr:not(:first-child, :last-child)').hover(function() { 
    $(this).find('td:not(:first-child, :last-child)').css("background", "red"); 
}, function() { 
    $(this).find('td:not(:first-child, :last-child)').css("background", ""); 
}); 

作爲一個小禮包,我發現我能轉換所有的jQuery代碼爲一條CSS規則(僅適用於現代瀏覽器):

table#tblSchoolList tr ~ tr:not(:last-child):hover td ~ td:not(:last-child) { 
    background: red; 
} 

當然,你總是可以保持你的jQuery的解決方案,如果你想用舊的瀏覽器兼容性或無法弄清上述CSS意味着:)

jsFiddle demo

+1

回覆:純CSS解決方案 - 你是一個生病,生病,男人;-) – Alnitak

+0

感謝您的信息。很好知道CSS規則也是如此。 – Gian

2

您可以嘗試使用slice,像這樣:

$('table#tblSchoolList tr').slice(1,-1).hover(function(){ 
    $(this).css("background", "red"); 
}, function(){ 
    $(this).css("background", ""); 
}); 

用負數指定從列表的末尾的偏移量。所以:

slice(
    1, // omit first row 
    -1 // omit last row 
) 

或者更簡單地說:

$('table#tblSchoolList tr').slice(1,-1).hover(function(){ 
    $(this).toggleClass('highlight'); 
}); 

(假設你有一個highlight類來處理色彩的行爲)。


編輯:更新,以確保第一和最後一列,以及行,不突出(感謝@boltclock):

$('#foo tr').slice(1,-1).hover(function(){ 
    $(this).find('td').slice(1,-1).toggleClass('highlight'); 
}); 

這裏是一個非常簡單的例子:http://jsfiddle.net/redler/Mgd8f/

+0

+1片'和'toggleClass' –

+0

那麼......那個td呢?現在你所做的只是重構OP已經有的東西。 – BoltClock

+0

@BoltClock,你是對的。錯過了。修訂。 –