Echoing the “then” state of variable in a mootools event even after var has changed

半腔热情 提交于 2020-01-17 12:41:11

问题


Let's take some pseudo-Mootools code:

for loop (i) from 0 to 5 {
    create.element {
        id: 'element_'+i
    }
    $('element_'+i).addevent.click {
        alert(i);
    }
}

The events get added to the elements properly. However, when clicked, they'll all alert the latest iterator... which would be 5.

Is there any way I can change "alert(i)" in the event to alert the iterator at that point in time?

.toString didn't do much.


回答1:


http://www.jsfiddle.net/dimitar/sbytJ/1/

for (var ii = 0; ii < 5; ++ii) {
    new Element("div#id_" + ii + ".monkey[text=click me]").store("id", ii).addEvent("click", function() {
        alert(this.retrieve("id") + " id: " + this.get("id"));
    }).inject(document.body);

}

using the element storage (element.store("id", ii) / this.retrieve("id")) is one way of ensuring correct value reference at runtime...

another way via an anonymous function: http://www.jsfiddle.net/dimitar/sbytJ/2/

for (var ii = 0; ii < 5; ++ii) {
    (function(id) {
        new Element("div#id_" + id + ".monkey[text=click me]").addEvent("click", function() {
            alert(id);
        }).inject(document.body);
    })(ii);
}

etc etc. i am sure there are other ways to refactor this also



来源:https://stackoverflow.com/questions/4054915/echoing-the-then-state-of-variable-in-a-mootools-event-even-after-var-has-chan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!