Javascript 如何在不触发更改事件的情况下选中复选框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5961625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:41:42  来源:igfitidea点击:

How do you check a checkbox without firing a change event?

javascriptextjsdom-events

提问by Bdfy

I have simple checkbox:

我有简单的复选框:

r = new Ext.form.Checkbox({
    listeners: {
        check: function(checkbox, checked) {
        }
    }
}

r.setValue(true);

How to check checkbox without fireevent check ( I want to fireevent check ONLY from mouse click ) ? (setValue doesn't work ).

如何在没有 fireevent 检查的情况下选中复选框(我只想通过鼠标单击来检查 fireevent)?(setValue 不起作用)。

回答by Selmaril

You should suspend events before set the value and resume events after this. For example:

您应该在设置值之前暂停事件并在此之后恢复事件。例如:

myCheckBox.suspendEvents(false); // Stop all events. 
                                 //Be careful with it. Dont forget resume events!
myCheckBox.setValue(!myCheckBox.getValue()); // invert value
myCheckBox.resumeEvents(); // resume events

回答by Lev

Why dont you just set

你为什么不设置

r.checked = true, 

does that not work? although it should work.

那不行吗?虽然它应该工作。

回答by VadimB

Why dont you just set r.checked = true, does that not work?

你为什么不直接设置 r.checked = true,那不行吗?

Setting checked attributes will have affect only for non-rendered control to assign initial control value. After rendering you can't use this to change value.

设置选中的属性只会影响非渲染控件分配初始控件值。渲染后,您不能使用它来更改值。

Suspend/Resume events is good practice to change control value without sending notifications.

暂停/恢复事件是在不发送通知的情况下更改控制值的好习惯。

Also you can put checked state immedially to dom element:

您也可以立即将检查状态放入 dom 元素:

item.el.dom.checked = true;

item.el.dom.checked = true;

回答by LUKE

I was already trying the accepted answer before googling but it didn't work in 4.1.3. The following did:

在谷歌搜索之前,我已经在尝试接受的答案,但它在 4.1.3 中不起作用。做了以下事情:

myCheckBox.setRawValue(true);

Hope this helps future googlers.

希望这有助于未来的谷歌员工。

回答by Douglas Mendes

Calling suspendEvents(false)before setting the value and resumeEvents()afterwards is a more generic approach than setRawValuebecause if you're using converters (say, 1is trueand 0is false) they will remain working.

suspendEvents(false)在设置值之前和resumeEvents()之后调用是一种更通用的方法,setRawValue因为如果您使用转换器(例如1istrue0is false),它们将继续工作。