【问题标题】:Explicit .trigger("click") is not setting checked to true jquery显式 .trigger("click") 未设置为 true jquery
【发布时间】:2020-09-23 09:49:07
【问题描述】:
在我的 js 文件中,当复选框上发生“单击”事件时会触发一个函数,并在单击时检查哪些值被“选中”并选择这些值。
我正在单击 :: $('#id').trigger("click"); or $('#id').click() 之类的代码,在这种情况下,调用“单击”时触发的函数,但是当它检查 if($('#id').checked) 时,它返回 false,并且“if-body”永远不会调用。
当我触发对复选框的点击时,为什么该元素的检查未设置为 true?
【问题讨论】:
标签:
javascript
jquery
jquery-ui
dom
checkbox
【解决方案1】:
因为$('#id') 没有checked 属性。所以$('#id').checked 是undefined。即使单击复选框本身,您也可以看到控制台undefined
$('#id').on('click', function() {
console.log($('#id').checked);
});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<input id="id" type="checkbox" />
有一些方法可以检查复选框是否被选中。
$('#id').on('click', function() {
console.log(
$('#id').is(':checked'),
$('#id').get(0).checked,
$('#id').prop('checked')
);
});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<input id="id" type="checkbox" />
还有按钮
$('#id').on('click', function() {
if ($('#id').is(':checked')) {
console.log('checked!!')
}
});
$('button').on('click', function() {
$('input').trigger('click');
})
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<input id="id" type="checkbox" />
<button>trigger check</button>