jQuery方法基于1.8.3
代码:
var radio = document.getElementById('myRadio'),
container = document.getElementById('container'),
str = '';
addRadio(radio);
//addRadioInjQuery('#myRadio');
//原生的实现方法
function addRadio(element) {
/*键盘更改部分*/
element.addEventListener('keyup', function (e) {
if ((e.which || event.keyCode) === 32) {
//isChecked记录radio应该变成的状态,
//this.checked=!this.checked触发change事件
this.isClicked = this.checked = !this.checked;
}
}, false);
/*鼠标部分*/
element.addEventListener('mouseup', function (e) {
this.isClicked = this.checked = !this.checked;
}, false);
element.addEventListener('change', function (e) {
this.checked = this.isClicked;
}, false);
}
//jQuery实现方法
function addRadioInjQuery(selector) {
$(selector).keyup(function (e) {
if ((e.which || event.keyCode) === 32) {
this.isClicked = this.checked = !this.checked;
}
}).mouseup(function (e) {
this.isClicked = this.checked = !this.checked;
}).change(function (e) {
this.checked = this.isClicked;
});
}