首页 > 解决方案 > HTML,Javascript - 单击按钮后如何保存变量

问题描述

请帮帮我。单击一次按钮后,我需要保存一个变量,并在按三次按钮后使用该保存的值。我有一个点击计数器,但在第二次点击后变量未定义。

if (clicks == 1){var bott(savethis)=correct;}

if (clicks == 3){var potom=this-spatne2;}

标签: javascriptbutton

解决方案


我真的不知道你发布的代码应该做什么(它在很多方面都不正确,所以它真的没有意义),所以我会根据你在问题中所说的内容来帮助你并假设这就是你想要的。如果不是,请告诉我:

// Declare these variables outside of the click function
// so that you can access them the whole time
var clicks = 0,
    correct = 42,
    bott;
    
// When the document is ready, execute `init`
window.addEventListener('DOMContentLoaded', init);

function init() {
  // When the user clicks on the button, execute `onButtonClick`
  document.getElementById('my-button').addEventListener('click', onButtonClick);
}

function onButtonClick() {
  // Add one to the number of clicks
  clicks++;
  if (clicks === 1) {
    // Notice I did not use `var` here, this is because `var` makes the variable
    // local to the function, and once the function's execution is over, it's destroyed.
    // Since I declared it a the top of this script, this is the one I'm referring to.
    bott = correct;
  } else if (clicks === 3) {
    alert('bott is equal to ' + bott);
  }
}
<button id="my-button">Click me!</button>


推荐阅读