【问题标题】:HTML, Javascript - How to save variable after one click on button [closed]HTML,Javascript - 单击按钮后如何保存变量[关闭]
【发布时间】:2019-01-03 20:54:43
【问题描述】:

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

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

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

【问题讨论】:

  • 你的密码broseidon在哪里?
  • var bott(savethis) 语法无效

标签: javascript button


【解决方案1】:

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

// 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>

【讨论】:

  • 正确也被认为是可变的。我的页面上有每次单击按钮时都会更改的数字。我需要在第一次点击后保存号码,第二次点击后不要取消定义,第三次点击后使用保存的号码。
  • @RvL 好的,我编辑了我的答案
  • @RvL 好。如果此答案解决了您的问题,请将其标记为已接受
猜你喜欢
  • 2013-07-13
  • 1970-01-01
  • 2017-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多