.addClass()
(私の意見では)最も簡単な方法は、 andを使用してクラスを適用または削除すること.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
})