简体   繁体   English

如果曾经点击过按钮,则运行一个函数,即使在页面重新加载时

[英]Run a function if a button has ever been clicked, even on page reload

I have a button:我有一个按钮:

<script>
function never(){
alert('This is place holding text');
}
</script>
<button onclick="never()">Understood</button>

I need to use local storage or cookies to remember if the button has ever been clicked, and if it has, to run the function and if it hasn't to not run the function until they click the button, I've had an idea...我需要使用本地存储或 cookie 来记住按钮是否被点击过,如果有,运行该功能,如果在他们点击按钮之前没有运行该功能,我有一个想法...

  1. Onload Run Function.加载运行功能。
  2. Check if button has been clicked, then run function.检查按钮是否被点击,然后运行函数。
  3. Else do not run function.否则不运行功能。
  4. If button is clicked set cookie or value to run function automatically now.如果单击按钮,则设置 cookie 或值以立即自动运行功能。

I have no idea how to actually implement this though, or if this won't work.我不知道如何实际实现这一点,或者这是否行不通。 And yes, I know the real solution would be server side, but I do not have a server.是的,我知道真正的解决方案是服务器端,但我没有服务器。

do u mean this way :你的意思是这样吗:

<button onclick="run()">Click</button>
function run(){
localStorage.setItem('item','value');
}

or something else ??或者是其他东西 ??

You can check this implementation您可以检查此实现

You can just store some value to localStorage when clicked and then read those values later.您可以在单击时将一些值存储到localStorage ,然后稍后read这些值。

HTML HTML

<button id="btn">Click Me</button>

JavaScript JavaScript

const btn = document.querySelector("#btn");

if(localStorage.getItem('clicked')) btn.innerText = 'clicked once';


btn.addEventListener('click', handleClick);

function handleClick(event) {
  if(localStorage.getItem('clicked')) return;
  else {
    localStorage.setItem('clicked', true);
    btn.innerText = 'clicked once';
  }
}

or try this way或尝试这种方式

 var someData = 'any data.'; localStorage.setItem('myData', '') function never(){ localStorage.setItem('myData', someData); alert('This is place holding text'); } var data = localStorage.getItem('myData'); if (data != ""){ never() } localStorage.removeItem('myData')
 <button onclick="never()">Understood</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM