javascript - HTML,Javascript - 单击按钮后如何保存变量
问题描述
请帮帮我。单击一次按钮后,我需要保存一个变量,并在按三次按钮后使用该保存的值。我有一个点击计数器,但在第二次点击后变量未定义。
if (clicks == 1){var bott(savethis)=correct;}
if (clicks == 3){var potom=this-spatne2;}
解决方案
我真的不知道你发布的代码应该做什么(它在很多方面都不正确,所以它真的没有意义),所以我会根据你在问题中所说的内容来帮助你并假设这就是你想要的。如果不是,请告诉我:
// 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>
推荐阅读
- android - 实时下载优化。如何找到泄漏点?
- ajax - 谷歌分析/标签管理器内部站点搜索 API
- excel - F1 在我的 Excel-VBA 中不起作用,我该如何解决?
- apache-kafka - \Java\jdk1.6.0_26\lib 此时出乎意料。在运行 apache kafka 时
- asp.net - MVC Repository 类中缺少显式强制转换
- python - 给定一个点列表 (x,y),创建一个新的点列表,这些点彼此不靠近
- redux - 在构建 redux 应用程序时,combineReducers 中 reducer 的顺序排列是否重要?
- arrays - 在给定数组中查找阈值
- delphi - Delphi TFileStream WriteBuffer Int64的大小不是吗?我一次只能写少量
- python - 如何使用 python-pptx 删除聚集条形图中的轴线?