效果實現共需三個文件:javascript
一、test.html 內容:html
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>Document</title> <script type="text/javascript" src="./jquery1.8.2.js"></script> <script type="text/javascript" src="./radioChecked.js"></script> </head> <body> <!-- <input type="radio" name="test" value="a" data-check="1"> <input type="radio" name="test" value="b" data-check="1"> <HR> <input type="radio" name="test1" value="c" data-check="1"> <input type="radio" name="test1" value="d" data-check="1"> <input type="radio" name="test1" value="e" data-check="1"> --> <input type="radio" name="test" value="a"> <input type="radio" name="test" value="b"> <HR> <input type="radio" name="test1" value="c"> <input type="radio" name="test1" value="d"> <input type="radio" name="test1" value="e"> </body> <script> $(function(){ $('.testch').click(function(){ $(this).radioChecked().init(); }); $('.testch').radioChecked().setDataAttr() }); </script> </html>
二、radioChecked.js 內容java
;(function($, window, document, undefined){ var MyPlugin = function(obj){ this.$object = obj, this.className = this.getClass(), this.elementName = this.getElementName() //this.options = $.extend({}, this.defaults, opt) } MyPlugin.prototype = { init: function() { if(this.$object.data('check') == '1'){ $(':radio[name="'+ this.elementName +'"]').each(function(){ $(this).data('check','1'); }); this.$object.data('check','2'); alert('選中'); } else if(this.$object.data('check') == '2'){ this.$object.data('check','1'); this.$object.removeAttr('checked'); alert('取消選中'); } }, getClass: function(){ return this.$object.attr('class'); }, getElementName: function(){ return this.$object.attr('name'); }, setDataAttr: function(){ $('.'+this.className).data('check','1'); } } $.fn.radioChecked = function(){ return new MyPlugin(this); } })(jQuery, window, document);
三、jquery1.8.2.jsjquery