javascript 复选框并触发更改事件javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19676525/
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
check checkbox and trigger change event javascript
提问by Sachin Verma
I want to trigger change event and check checkbox from javaScript not jQuery.
I am having issues with jQuery because of this Strange Behaviour.
What i used to do with jQuery is:
我想从javaScript 而不是 jQuery触发更改事件和复选框。
由于这种奇怪的行为,我在使用 jQuery 时遇到了问题。
我曾经用 jQuery 做的是:
$('#laneFilter').prop('checked','true').trigger('change');
I want same to do with javaScript. This must be really simple but i could not find the way . please help thanks in advance
我想用 javaScript 做同样的事情。这一定很简单,但我找不到方法。请帮助提前致谢
回答by Ishan Jain
There's a couple of ways you can do this. The easiest method is to just call that function:
有几种方法可以做到这一点。最简单的方法是调用该函数:
var Chkinput = document.getElementById("laneFilter");
Chkinput .onchange();
If you need it to simulate the real event in full, or if you set the event via the html attribute or addEventListener
/attachEvent
, you need to do a bit of feature detection to correctly fire the event:
如果您需要它来完全模拟真实事件,或者如果您通过 html 属性或addEventListener
/设置事件attachEvent
,则需要进行一些功能检测以正确触发事件:
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
element.dispatchEvent(evt);
}
回答by schnawel007
<input type="checkbox" id="laneFilter"/>
<script>
checkbox = document.getElementById("laneFilter");
checkbox.onclick = function(){
alert('lol');
};
checkbox.checked = true;
</script>
should also work
也应该工作
回答by Amila
I cut it to 2 then work fine
我把它切成 2 然后工作正常
$('#laneFilter').prop('checked','true');
$('#laneFilter').trigger('change');
回答by Yevgeniy Afanasyev
Just call change function without parameters.
只需调用不带参数的更改函数。
$('#laneFilter').change('change', function(){
debugger
...
}).change();
it works in "jquery": "3.3.1"
它适用于“jquery”:“3.3.1”