传递变量到事件javascript - 没有闭包,没有jq,避免evals&这样 [英] pass variables to an event javascript - no closures, no jq, avoid evals & such

查看:124
本文介绍了传递变量到事件javascript - 没有闭包,没有jq,避免evals&这样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确定,这已经被大家解决了,但是我觉得没有更接近理解怎么做。

ok, this has been addressed by everybody, but yet I feel no closer to understanding what to do.

我想要一个循环,设置一堆点击处理程序,并为每个处理程序提供唯一的参数。我现在做这样的事情:

I want to have a loop that sets a bunch of click handlers and have each handler given unique parameters. I'm doing somehting like this now:

for (thisThing in things){
    myDiv=document.createElement('img');

    myDiv.onclick=function(){
        // do somehting!
        // but don't do anything with "thisThing" 
        // because it's got the wrong value in it by the time you call it!
        // but this function has to have the value of "thisThing" to work, dammit!
    }
}




  • 这个解决方案据说是封闭 - 哇伟大!除非闭包破坏ie(right?)

  • 同样,我可以在现场评估代码,烘焙在可变性,但这似乎丑陋的,最好的,似乎可能打破一些事

  • 这是什么让我失望?是闭合确定吗?是evaling确定?我只有人在网络上动态创建按钮吗?!?任何帮助将非常感激。对不起的基本和事实上,经常回答的问题。

    So what does this leave me? Are closures ok? is evaling ok? AM I THE ONLY PERSON DYNAMICALLY CREATING BUTTONS ON THE WEB?!? Any help will be much appreciated. sorry about the elementary &, in fact, frequently answered question.

    这个页面是我到目前为止找到的最完整的答案,但是,它表明闭包是所有时间的解决方案。诅咒! http://www.howtocreate.co.uk/referencedvariables.html

    this page has the most complete answer I've found thus far, however, it suggests that closures are the solution for all time. Curses! http://www.howtocreate.co.uk/referencedvariables.html

    推荐答案

    关闭不会打破IE。

    Closures do not break IE.

    (function(someThing) {
        myDiv.onclick=function(){
           // Access it as "someThing"
        }
    })(thisThing);
    

    jsFiddle

    问题是分配给 onclick 属性的函数创建一个闭包

    The problem is the function assigned to the onclick property creates a closure where it has access to its parents variables.

    当你准备点击一个元素时,它的 thisThing 已经递增到终止循环的最终值(在您的情况下迭代的最后一个属性),因为它访问外部变量而不是副本。

    By the time you are ready to click an element, its thisThing has been incremented to the final value that terminates the loop (the last property iterated over in your case) because it accesses the outer variable, not a copy.

    通过使用新的自我调用函数创建一个新的闭包,并传递 thisThing ,其值将变为 someThing 并且只在内部函数里面。

    By creating a new closure with a new self invoking function and passing thisThing, its value becomes the variable someThing and lives inside of the inner function only.

    这是缓解这个已知问题的方法之一。

    This is one of the ways of mitigating this known problem.

    请注意,在IE6& 7有内存泄漏。请咨询 RobG Raynos的回答解决这个问题。

    Note that in IE6 & 7 there is a memory leak. Consult RobG or Raynos's answer for a solution to this issue.

    这篇关于传递变量到事件javascript - 没有闭包,没有jq,避免evals&这样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆