单击按钮仅重新加载页面一次

时间:2016-06-28 18:48:07

标签: javascript

我有一个加载按钮,我在该按钮上调用onclick事件,该事件将使用window.location.reload()刷新页面。但是,我想要的是只有在第一次点击按钮时才会调用重新加载。从第二次单击开始,直到HTML页面处于活动状态,不应调用重新加载。

如何通过javascript实现这一目标?任何示例都会有所帮助。

4 个答案:

答案 0 :(得分:1)

您可以使用local storagesession storage来执行此操作。这是一种利用Web Storage API的现代方法。

在这种情况下,您可以在存储中设置一个属性来保持按钮单击,只有在尚未单击时才进行刷新。

可以像以下代码段一样进行:

$('button').on('click', function() {
    // will return null at the first call
    var buttonClicked = sessionStorage.getItem('isButtonClicked');

    // will only enter if the value is null (what is the case in the first call)
    if (!buttonClicked) {
        // set value to prevent further reloads
        sessionStorage.setItem('isButtonClicked', true);

        // reload the page
        window.location.reload();
    }
});

如果您想了解有关它的更多详细信息,可以在here找到有关网络存储API的更详细示例。

答案 1 :(得分:0)

处理此问题的一种方法是更改​​onClick执行的操作。试着看看这里:Change onclick action with a Javascript function

答案 2 :(得分:0)

您可以尝试在第一次重新加载时发送参数,并使用该参数更改按钮的操作。

类似的东西:

<script>
function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
  return false;
}
var secondReload= getQueryVariable("secondReload");
if(!secondReload){
 //if button clicked
 window.location.reload();
}else{
//deactivate button
}
</script>

答案 3 :(得分:-2)

您需要在点击事件中的按钮标记上添加禁用属性。

Reloading the page only once on a button click

如果你正在使用jQuery,就像这样。

&#13;
&#13;
$('button').on('click',function()({
... your code here
$(this).attr('disabled');
});
&#13;
&#13;
&#13;

相关问题