我有一个问题,我想记住 jQuery UI 对话框弹出窗口中选中的单选按钮。
我遇到了一些奇怪的行为,所以我在 JSFiddle 中模拟了它。 fiddle 在创建时基本上会随机选择 3 个 radio 选项之一。然而它很快就会停止工作。
我也尝试过使用和不使用removeAttr('checked') 的行。
您需要多次单击打开对话框并关闭它才能看到它停止工作。我已经在最新版本的 Chrome 中对此进行了测试。
HTML
<div id="dialog" style="display:none;">
<input type="radio" class="left" name="rentFrequency" value="1" />
<span class="left"> Monthly   </span>
<input type="radio" class="left" name="rentFrequency" value="2" />
<span class="left"> Quarterly   </span>
<input type="radio" class="left" name="rentFrequency" value="3" />
<span class="left"> Annualy   </span>
</div>
<input type="button" name="dialogOpen" value="Open Dialog" />
<input type="text" name="randVal" value="" readonly="readonly" />
Javascript
$(document).ready(function() {
$('input[name="dialogOpen"]').click(function(){
$("#dialog").dialog({
title: 'Additional Tenancy Information',
resizable: false,
width: 530,
show: { effect:'fade', duration:500 },
hide: { effect:'fade', duration:400},
modal: true,
close: function (event, ui) {
},
open: function (event, ui) {
var randval=Math.floor(Math.random()*3)+1
console.log(randval);
$('input[name="randVal"]').val(randval);
$('input[name="rentFrequency"]').removeAttr('checked');
$('input[name="rentFrequency"][value="'+randval+'"]').attr('checked', 'checked');
}
});
});
});
这实际上是相同的代码,只是没有弹出对话框,并且其行为符合预期:
只要一直点击“运行”
最佳答案
跟进我的评论。将 attr 实例更改为 prop
$('input[name="randVal"]').val(randval);
$('input[name="rentFrequency"]').prop("checked", false);
$('input[name="rentFrequency"][value="'+randval+'"]').prop("checked", true);
关于jQuery 对话框设置 radio 检查问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15342158/