首页 > 解决方案 > 如果页面刷新,则取消设置 PHP 按钮 onclick="this.disabled=true"

问题描述

如果页面刷新,我不想取消设置onclick="this.disabled=true" ,

代码 :

<button type="button" class="addb btn btn-primary rounded-pill py-2 btn-block" type="submit"  data-voice_sku="'.$row["voice_sku"].'" data-voice_name="'.$row["voice_name"].'" onclick="this.disabled=true">Add to Playlist</button>

如果页面刷新 onclick 事件未设置。如何预防?

标签: onclick

解决方案


我会为此使用 localStorage。这是一个基本示例:

<button id="myBtn" type="button" onclick="disable_btn(this);">Add to Playlist</button>


<script>
    // disable the button on page load
    (function() {
        if(window.localStorage.getItem('myBtn') == 'true'){
            document.getElementById('myBtn').disabled=true;
        }
    })();

    // function to disable button when clicked
    function disable_btn(el){
        el.disabled=true;
        window.localStorage.setItem('myBtn', true);
    }

</script>

以及多个按钮的示例:

<button id="btn1" type="button" onclick="disable_btn(this, 'btn1');">Add to Playlist 1</button>
<button id="btn2" type="button" onclick="disable_btn(this, 'btn2');">Add to Playlist 2</button>
<button id="btn3" type="button" onclick="disable_btn(this, 'btn3');">Add to Playlist 3</button>


<script>
    // disable disabled buttons on page load
    (function() {
        var buttons = document.querySelectorAll('button')
        for (var i = 0; i < buttons.length; ++i) {
            if(window.localStorage.getItem(buttons[i].id) == 'true'){
                buttons[i].disabled=true;
            }
        }
    })();

    // function to disable button when clicked
    function disable_btn(el, id){
        el.disabled=true;
        window.localStorage.setItem(id, true);
    }

</script>

这样,禁用的按钮将始终对该用户保持禁用状态,除非他清除浏览器缓存。


推荐阅读