Jquery-ui buttonset click事件似乎不会改变选中的状态

jquery-ui buttonset click event doesn't seem to change the checked state

本文关键字:改变 状态 click buttonset 事件 Jquery-ui      更新时间:2023-09-26

我使用一个jquery-ui按钮与2单选按钮是/否输入。

var yesInput = document.createElement("input");
yesInput.type = "radio";
$(yesInput).attr('id', "njs1");
$(yesInput).prop('checked', this._data);
var noInput = document.createElement("input");
noInput.type = "radio";
$(noInput).attr('id', "njs2");
$(noInput).prop('checked', !this._data);

我在这些按钮上调用一个更改事件,并在处理函数中试图检测选中的按钮是否被单击。buttonSet是组成buttonset()的div。

$("input[type=radio]", buttonSet).change(checkHandler);

var data= $("input[type=radio]", buttonSet).eq(0).is(':checked');

在这种情况下,我希望如果单击第二个按钮,data应该返回false。我的理解是,当我检查收音机时,它的html被修改为添加checked

然而,不管调用什么,数据总是true

我做错了什么?如何得到正确的值?

编辑:

示例小提琴

如你所见,我可以点击No,仍然选中Yes。因为它是一个单选,所以我希望它的行为是这样的

为什么不使用jQuery的方式创建元素?对单选按钮使用单击事件。

$('<input/>').attr({type: "radio", "id": "njs1"})
.prop("checked", !this._data)
.click(checkHandler);

要将输入元素更改为选中状态,必须使用To .prop()

设置为checked: $( "input" ).prop( "checked", true );

设置为未检查: $( "input" ).prop( "checked", false );

http://api.jquery.com/prop/

在jQuery 1.6之前,.attr改变了html属性和dom属性。

从v1.6开始,这个行为已经改变了。

属性和属性之间的区别在具体的情况。在jQuery 1.6之前,.attr()方法有时在检索某些属性时考虑了属性值,这可能导致不一致的行为。从jQuery 1.6开始,.prop()方法提供了显式检索属性值的方法,而.attr()检索属性。

两个无线电输入应该有完全相同的值,以便将它们分组在一起。

$(yesInput).attr('id', "njs1"); $(yesInput).attr('name', "toggle"); // << shared name $(noInput).attr('id', "njs2"); $(yesInput).attr('name', "toggle"); // << shared name