我正在使用一些代码将单选按钮显示为图像:
HTML:
<div id="skin_1" title="Walk">
<input type="radio" name="travel_mode" id="mode_walking" value="WALKING" /><br>
Walk
</div>
<div id="skin_2" title="Drive">
<input type="radio" name="travel_mode" id="mode_driving" value="DRIVING" /><br>
Drive
</div>
<div id="skin_3" title="Bike">
<input type="radio" name="travel_mode" id="mode_bicycle" value="BICYCLING" /><br>
Bike
</div>
<div id="skin_4" title="Transit">
<input type="radio" name="travel_mode" id="mode_transit" value="TRANSIT" /><br>
Transit
</div>
<div>
<a href="#" onClick="testMe();">What mode is selected?</a>
</div>
JS:
$(function () {
$('input:radio').hide().each(function () {
var label = $("label[for=" + '"' + this.id + '"' + "]").text();
$('<a ' + (label != '' ? 'title=" ' + label + ' "' : '') + ' class="radio-fx ' + this.name + '"><span class="radio' + (this.checked ? ' radio-checked' : '') + '"></span></a>').insertAfter(this);
});
$('.radio-fx').on('click', function (e) {
$("input[name=travel_mode]").removeAttr("checked"); // add this line
$check = $(this).prev('input:radio');
var unique = '.' + this.className.split(' ')[1] + ' span';
$(unique).attr('class', 'radio');
$(this).find('span').attr('class', 'radio-checked');
this.blur();
this.focus();
$check.attr('checked', true);
getDirections();
}).on('keydown', function (e) {
if ((e.keyCode ? e.keyCode : e.which) == 32) {
$(this).trigger('click');
}
});
});
此代码在除 IE 之外的所有浏览器中都可以正常工作。在 IE 中,第二次单击单选按钮后,该值为“未定义”。
我尝试使用:
this.blur();
this.focus();
按照其他建议,但这不起作用。
如何解决这个问题,使其在 IE 中也能正常工作?
最佳答案
使用 prop 代替 attr
$(function () {
$('input:radio').hide().each(function () {
var label = $("label[for=" + '"' + this.id + '"' + "]").text();
$('<a ' + (label != '' ? 'title=" ' + label + ' "' : '') + ' class="radio-fx ' + this.name + '"><span class="radio' + (this.checked ? ' radio-checked' : '') + '"></span></a>').insertAfter(this);
});
$('.radio-fx').on('click', function (e) {
$("input[name=travel_mode]").prop('checked', false);; // add this line
$check = $(this).prev('input:radio');
var unique = '.' + this.className.split(' ')[1] + ' span';
$(unique).attr('class', 'radio');
$(this).find('span').attr('class', 'radio-checked');
this.blur();
this.focus();
$check.prop('checked', true);
getDirections();
}).on('keydown', function (e) {
if ((e.keyCode ? e.keyCode : e.which) == 32) {
$(this).trigger('click');
}
});
});
关于javascript - 第二次单击后,单选按钮值在 IE 中不正确。在其他浏览器中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39524343/