如果刷新页面,则未设置PHP Button onclick =“ this.disabled = true”

时间:2019-09-28 10:59:28

标签: onclick

如果页面刷新,我不想取消设置 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事件未设置。如何预防?

1 个答案:

答案 0 :(得分:1)

我将为此使用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>

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