.attr('checked',true)单击按钮时不会重新添加

时间:2019-03-01 16:07:00

标签: javascript jquery

我有一个带有“重置”按钮的form。当我选择我的radio button时,我的DataTable中的数据将被传递并预弹出我的字段。这样工作正常,实际上确实预填充了相关的单选按钮

jQuery

if (modifyRecordData.startTime == 'Anytime') {
    $('#anyTimeRadioButton').attr('checked', true);
    $('#specificTimeRadioButton').removeAttr('checked');
    $('#startEndTimeFields').hide();
} else {
    $('#anyTimeRadioButton').removeAttr('checked');
    $('#specificTimeRadioButton').attr('checked', true);
    $('#startEndTimeFields').show();
    $('#startTimeHr').val(modifyRecordData.startTimeHr);
    $('#startTimeMin').val(modifyRecordData.startTimeMin);
    $('#endTimeHr').val(modifyRecordData.endTimeHr);
    $('#endTimeMin').val(modifyRecordData.endTimeMin);
}

返回的数据

enter image description here

页面已加载 enter image description here

现在的问题是,如果用户在数据加载之后更新详细信息并选择另一个单选按钮,则会显示隐藏字段(再次正确) enter image description here

然后用户单击“重置”按钮,它将失败,显示正确的function

$('#resetButton').mousedown(function (event) {
    buttonclicked = "Reset";
    event.stopImmediatePropagation();
    modifyRadioButtonSelection(modifyRecordData);
})

,然后返回到初始加载的数据,并确实将其放入上面的IF代码中

调试 enter image description here

然后它重新隐藏了隐藏的部分(这是正确的),但没有按预期重新选中radio button

enter image description here

如果我在IF中没有以下代码,尽管数据落入IF

中,它仍使先前选择的代码处于选中状态
$('#specificTimeRadioButton').removeAttr('checked');

完全不知道出了什么问题。我什至尝试添加以下“重置”按钮function,但只是不会重新检查正确的“单选按钮”

$('#anyTimeRadioButton').removeAttr('checked');
$('#specificTimeRadioButton').removeAttr('checked');

1 个答案:

答案 0 :(得分:3)

从历史上看,三个相关但不同的概念之间存在很多歧义和困惑:

  • 源代码中HTML属性的值。
  • DOM树中HTML属性的值。
  • JavaScript属性的值。

为解决这个问题,jQuery / 1.6.1引入了prop() method,我建议您采用它。