[英]How save value of a variable in javascript after executing a method?
I have this code : 我有这个代码:
var n = 0; // << I want save value of this var $('.next').click(function () { // << after this method run n++ }); function run() { setInterval(function () { n++; var slideId = '#' + "slide" + (n); var dotId = '#' + "dot" + (n); if (n == settings.slideNumber) { n = 0; } var lastSlideId = '#' + "slide" + (n + 1); var lastDotId = '#' + "dot" + (n + 1); $(slideId).css({display: 'none'}); $(dotId).css({backgroundColor: '#1a1a1a'}); $(lastSlideId).css({display: 'block'}); $(lastDotId).css({backgroundColor: '#0AC986'}); }, 2000); } run();
After the click event occurred , run method will start from fist and value of n will be zero again . 在click事件发生后,run方法将从第一拳开始,并且n的值将再次为零。 How i can save the value of n var after click event ?
单击事件后如何保存n var的值? ( Consider that I wrote this method inside a jquery plugin )
(考虑到我在一个jQuery插件中写了这个方法)
You can declare n
as the global variable, to keep up to date with the latest value of n. 您可以将
n
声明为全局变量,以保持最新的n值。
Also, the click
event should be outside of the run
function, otherwise, each time you execute run
function it will attach a new event listener for the button click
. 另外,
click
事件应该在run
函数之外,否则,每次执行run
函数时,它将为button click
附加一个新的事件侦听器。
I have created a sample as per your question. 我根据您的问题创建了一个样本。 Hope it helps.
希望能帮助到你。
let n = 0; $('#btn').click(function() { n++; console.log("Value of n::",n) }); function run() { console.log("Value of n::",n) } run(); $('#run').click(run);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="btn">Click</button> <button id="run">Run</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.