【问题标题】:How to enable/disable a button via checkbox and keep the button active or inactive after refreshing the page如何通过复选框启用/禁用按钮并在刷新页面后保持按钮处于活动或非活动状态
【发布时间】:2021-06-18 18:16:41
【问题描述】:

我有一个按钮,我想做以下事情

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

我找到了两个完全符合我需要的参考,但我不知道如何将这两个解决方案放在一起。 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'));
    });

非常感谢!

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    这会在 sn-p 中产生一个脚本错误,可能是因为它是一个沙盒并且不允许 localStorage。但这已经过测试并且有效。解释见代码中的 cmets。您可以将复选框设置为打开或关闭,当您刷新页面时,它会“记住”它的状态

    $(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>

    【讨论】:

    • 完美运行!谢谢你。我仍然无法为您的答案投票,因为我今天创建了自己的帐户,但一旦我得到它,我就会回到这里去做。
    • 谢谢。我认为您可以接受答案(只是由于“声誉”不足而尚未投票)-只需单击答案左侧的小复选标记(除非我弄错了)-meta.stackexchange.com/questions/5234/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 2022-01-23
    • 2019-12-31
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多