Explicit .trigger(“ click”)未设置为true选中为jquery

问题描述 投票:0回答:1

在我的js文件中,当复选框上发生“单击”事件时,会触发一个函数,并在该单击上检查“选中”了哪些值并选择了这些值。在这种情况下,我正在执行诸如:: $('#id').trigger("click"); or $('#id').click()之类的单击代码,将调用在“ click”上触发的函数,但是当它检查if($('#id').checked)时,此函数将返回false,并且永远不会显示“ if-body”叫。

为什么当我触发复选框单击时,为什么未将该元素设置为true?

javascript jquery jquery-ui dom checkbox
1个回答
2
投票

因为$('#id')没有checked属性。所以$('#id').checkedundefined。您可以看到,即使单击复选框本身的控制台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>
© www.soinside.com 2019 - 2024. All rights reserved.