最簡單的(在我看來)方法是使用.addClass()
和.removeClass()
來申請或刪除一個班級。然後,您可以使用CSS來設置顏色和任何其他設置的格式。
function showonlyone(thechosenone) {
$('.newboxes').each(function (index) {
if ($(this).attr("id") == thechosenone) {
$(this).addClass("highlight");
} else {
$(this).removeClass("highlight");
}
});
}
而在你的CSS後:
.highlight a { /* may need to format differently depending on your HTML structure */
color: #ff0000; /* red */
}
您還可以簡化您的代碼如下所示:
function showonlyone(thechosenone) {
$('.newboxes.highlight').removeClass("highlight"); // Remove highlight class from all `.newboxes`.
$('#' + thechosenone).addClass("highlight"); // Add class to just the chosen one
}
此代碼將等待DOM加載,然後應用「高亮「級首次亮相<div class="newboxes">
:
$(document).ready(function(){
$(".newboxes:first").addClass("highlight");
// The :first selector finds just the first object
// This would also work: $(".newboxes").eq(0).addClass("highlight");
// And so would this: $(".newboxes:eq(0)").addClass("highlight");
// eq(n) selects the n'th matching occurrence, beginning from zero
})
你能提供一些HTML代碼示例,以顯示您的確切標記?你可以創建一個[jsfiddle](http://www.jsfiddle.net) – SirDerpington 2013-04-29 20:27:22