標籤:style blog color io os ar sp div on
//外掛程式代碼
;(function($){ $.fn.extend({ "alterBgColor":function(options){ options = $.extend({ "odd":"odd",//偶數行的class "even":"even",//奇數行class "selected":"selected"//被點擊行class },options);//傳入的class參數替換預設的class設定 console.info(options) $("tbody tr:odd").addClass(options.odd);//偶數行設定class $("tbody tr:even").addClass(options.even);//奇數行設定class $("tbody tr").click(function(){//table行的點擊事件 //當前點擊行添加selected樣式,其他行去除selected樣式,end()指的是對象又為$(this),該行的radio被選中 $(this).addClass(options.selected).siblings().removeClass(options.selected).end().find(":radio").attr("checked",true); }); //頁面載入時預設選中行的樣式 $("table :radio:checked").closest("tr").addClass(options.selected); return this;//返回this,使方法具有可鏈性 } })})(jQuery);
樣式:
table{ border: 1px gray solid; width: 500px; height: 400px; text-align: center; margin: 0 auto; } .odd{background-color: gainsboro;} .even{background-color: #FFFFEE} .selected{background-color:gold}
html:
<table> <thead> <tr> <th></th> <th>姓名</th> <th>性別</th> <th>暫住地</th> </tr> </thead> <tbody> <tr> <td><input type="radio" name="radio"></td> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td><input type="radio" name="radio"></td> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td><input type="radio" name="radio"></td> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td><input type="radio" name="radio"></td> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td><input type="radio" name="radio"></td> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td><input type="radio" name="radio"></td> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td><input type="radio" name="radio"></td> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td><input type="radio" name="radio"></td> <td>1</td> <td>2</td> <td>3</td> </tr> </tbody> </table>
<script>中的代碼
$(function(){ $("table").alterBgColor();//調用外掛程式,可以自己制定樣式,以"{}"對象參數的方式傳遞 });
注意:頁面需首先引入jquery庫
jquery的選擇符可能會匹配1個或多個元素,因此,外掛程式必須考慮這些情況。可以在外掛程式內部調用each()方法來遍曆匹配元素,然後執行相應的方法,this會依次引用每個dom元素
如下jquery代碼所示:
;(function($){ $.fn.extend({ "pluginName" : function(options){ return this.each(function(){ //這裡放置外掛程式代碼 }); } });})(jQuery);)
jquery表格隔行變色外掛程式