動態切換樣式是前端相當常見的需求,而最直覺的做法就是操作元素的 className。本文以 jQuery 為例,示範如何透過 class 的增刪來實作選取、全選與取消全選等效果。
先來看 HTML 結構,這裡有幾個帶共用 class 的連結,以及一組「全選/全不選」的按鈕:
<table> <tbody> <tr> <td>js實現class的樣式的修改、添加、刪除</td> <td> <a e_value="g_sn" ename="商品編碼" class="goods_sale_property" href="javascript:void(0);">商品編碼</a> <a e_value="pdt_sn" ename="商品貨號" class="goods_sale_property" href="javascript:void(0);">商品貨號</a> <a e_value="pdt_name" ename="規格名稱" class="goods_sale_property" href="javascript:void(0);">規格名稱</a> </td> </tr> </tbody> <tbody> <tr> <td><a onclick="selectAll()">全選</a></td> <td><a onclick="selectNotAll()">全不選</a></td> </tr> </tbody> </table>
接著透過 jQuery 的 addClass、removeClass 與 hasClass 來切換選取狀態。單擊某個連結時反轉它的 class,全選則替所有項目加上 class,全不選則移除:
<script>
$('.goods_sale_property').click(function(){ // 單擊切換 class
if($(this).hasClass('goods_sale_property_checked')){
$(this).removeClass('goods_sale_property_checked');
}else{
$(this).addClass('goods_sale_property_checked');
}
});
function selectAll(){ // 全選:加上 class
$('.goods_sale_property').each(function(){
$(this).addClass('goods_sale_property_checked');
});
}
function selectNotAll(){ // 全不選:移除 class
$('.goods_sale_property').each(function(){
$(this).removeClass('goods_sale_property_checked');
});
}
</script>
只要在 CSS 中為 .goods_sale_property_checked 定義好外觀,切換 class 就能立即反映到畫面上,這是操作樣式最流暢的方式之一。