如何通过复选框启用/禁用按钮并在刷新页面后保持按钮处于活动状态或非活动状态

时间:2021-06-18 18:16:41

标签: javascript jquery

我有一个按钮,我想执行以下操作

  • 通过单击引用它的复选框禁用此按钮
  • 即使在刷新页面后也保持禁用
  • 做同样的事情,但相反。该按钮已禁用,现在我想通过单击引用它的复选框再次启用它,刷新页面后保持这种状态

我找到了两个完全符合我需要的参考资料,但我不知道如何将这两个解决方案放在一起。 Thisthis

HTML 代码

<div id="billing">
    <input type="checkbox" id="billing-checkbox" checked>
    <input type="button" value="Hello Javascript!">
</div>

Javascript 代码

document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('billing-checkbox').onchange = toggleBilling;
    }, false);

    function toggleBilling() {
    var billingItems = document.querySelectorAll('#billing input[type="button"]');

    for (var i = 0; i < billingItems.length; i++) {
        billingItems[i].disabled = !billingItems[i].disabled;
    }
    }

    $(function(){
        var test = localStorage.input === 'true'? true: false;
        $('input').prop('checked', test || false);
    });

    $('input').on('change', function() {
        localStorage.input = $(this).is(':checked');
        console.log($(this).is(':checked'));
    });

非常感谢!

1 个答案:

答案 0 :(得分:1)

这将在代码段中出现脚本错误,可能是因为它是一个沙箱并且不允许使用 localStorage。但这已经过测试并且有效。有关解释,请参阅代码中的注释。您可以打开或关闭复选框,当您刷新页面时,它会“记住”它的状态

$(document).ready(function() {
  // first thing is to set the checkbox based on the localStorage key that we may have set in the past
  $('#billing-checkbox').prop('checked', localStorage.getItem('buttonDisabled') !== "disabled");

  // then we run our toggle billing
  toggleBilling()

  // we set up our change handler. 
  $('#billing-checkbox').on('change', toggleBilling);
});

function toggleBilling(e) {
  // we set the disabled based on the check button status
  $('#billing input[type="button"]').attr('disabled', !$('#billing-checkbox').prop('checked'))

  // we set the localStorage based on the button disabled
  localStorage.setItem('buttonDisabled', $('#billing input[type="button"]').attr('disabled'));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="billing">
  <input type="checkbox" id="billing-checkbox" checked>
  <input type="button" value="Hello Javascript!">
</div>