如果选中元素并重新加载页面,则单击事件

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

只有选中复选框,我才想要一个reload.location点击事件。对我而言,这似乎是基本条件,但它不起作用。也许需要一种不同的方法?我想通了,当勾选复选框时,<input type="checkbox">元素中没有html更改。也许这就是原因,或者这些条件的组合是不可能的? else语句是回调到之前的UI页面。在下面的尝试中,它正在跳过if语句。

我的尝试:

$(document.body).on("click", "#button", function(){
        if (document.getElementById('checkbox').checked) {

                location.reload(true);

        } else {

        return_to_page( this.dataset.return )

        }
    });

上面工作正常,但由于缺少preventDefault而被忽略:

$(document.body).on("click", "#button", function(e){
    e.preventDefault();

    //etc

});
if-statement click reload checked
2个回答
1
投票

checked不是jQuery对象的属性。您可以使用prop()获取酒店:

$('#button').click( function() {
  if ($('#checkbox').prop('checked')) {
    location.reload(true);
  }

  // alternative #1 - use the 'checked' property of the Element in the jQuery object:
  if ($('#checkbox')[0].checked) {
    location.reload(true);
  }

  // alternative #2 - use the 'checked' property of the Element outside of jQuery:
  if (document.getElementById('checkbox').checked) {
    location.reload(true);
  }
});

这是一个有效的例子:

$('#button').click(function() {
  if ($('#checkbox').prop('checked')) {
    // location.reload(true);
    console.log('Reload would happen now...');
  } else {
    console.log('Staying on the current page');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
  <input type="checkbox" id="checkbox" /> 
  Reload?
</label>
<button id="button">Go</button>

0
投票
$('#button').click( function() {
    if( $("input[id='checkbox']:checked") ) {
        location.reload(true);
    }
});

替代

$('#button').click( function() {
    if( $('#checkbox').is(':checked') ) {
        location.reload(true);
    }
});

所有在一个板块方法:

$('#checkbox').is(":checked")

$('#checkbox').prop('checked')

$('#checkbox')[0].checked

$('#checkbox').get(0).checked
© www.soinside.com 2019 - 2024. All rights reserved.