即使选中复选框,也会出现错误

Getting an error even when checkbox is checked

本文关键字:错误 复选框      更新时间:2023-09-26

在我找到的所有示例中,如果选中复选框,则使用is(':checked')应返回true,如果不选中,则返回false。在我的情况下,它在两种情况下都返回false。我犯了什么错?

          {
            xtype: 'checkbox',
            boxLabel: 'Show message',
            id: 'mainBox',
            handler: function() {
                alert($(this).is(':checked'));
          }

根据ExtJS文档,我会尝试以下操作:

{
    xtype: 'checkbox',
    boxLabel: 'Show message',
    id: 'mainBox',
    handler: function (field , value) {
        alert(value);
    }
}

因为extjs事件处理程序中的this不引用dom元素,this将引用extjs复选框对象。jQuery将无法使用extjs对象引用找到目标元素。相反,您有checkbox的getValue()方法,它将返回选中的状态值,因此

尝试

{
    xtype: 'checkbox',
    boxLabel: 'Show message',
    id: 'mainBox',
    handler: function (el) {
        alert(el.getValue());
    }
}

正如您在jQuery文档中所读到的,.is('…')函数返回一个jQuery对象。

如果您想要某种布尔值作为返回值,您可以尝试以下代码:

alert($(this).is(':checked').length > 0);

但对于checkbox元素,使用"checked"属性也应该有效:

alert(this.checked);

如果你想使用jQuery:,你甚至可以尝试一下

alert($(this).attr('checked') === 'checked');