Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

javascript - 用应该冻结其值的变量定义函数(Defining a function with a variable whose value should be frozen [duplicate])

This question already has an answer here:(这个问题已经在这里有了答案:)

JavaScript closure inside loops – simple practical example 44 answers(循环内的JavaScript封闭-简单的实际示例 44个答案)

Look at the following code.(看下面的代码。)

for(i=1;i<=10;i++){ $('#field'+i).click(function(){ alert(i); }); } When I click one of those fields I get an 11. Of course I know why: Because at the moment I click it the value of the variable i is 11. But I guess you know what I actually want.(当我单击这些字段之一时,我得到11。当然,我知道为什么:因为现在单击它,变量i值为11。但是我想您知道我真正想要的。) How do I do that?(我怎么做?)   ask by principal-ideal-domain translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use let to limit your i within the loop scope.(使用let将您的i限制在循环范围内。)

That would solve your problem.(那将解决您的问题。) for(let i=1;i<=10;i++){ setTimeout(function(){ console.log(i) }, 500); }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...