javascript - Setting up onclick handlers into for -
this question has answer here:
i have array this.conds = ["addr", "acc"]
example. have these dom
objects in html tree. piece of code:
for(cond in this.conds) { this.searchby[this.conds[cond]] = { "btn": $("#" + this.conds[cond] + "btn"), "fields": $("#" + this.conds[cond] + "fields"), "active": false }; // handlers __this = this; this.searchby[this.conds[cond]].btn.click(function() { __this.setallunactive(); __this.searchby[__this.conds[cond]].active = true; __this.searchby[__this.conds[cond]].fields.show(); }); }
i cant make handler handle current element of this.conds
. handle last element every time. how avoid wrong behavior?
this pretty common javascript pitfall. js doesn't have block context; variables set in block go surrounding context. have few options here:
- use
$.each()
loop, takes function, , consequently keeps context. - use
[].foreach()
, similar$.each()
, native js. (note: not available in older browsers.) - wrap each iteration in function, this
function handlecond(cond) { // put code here } for(cond in this.conds) { handlecond(this.conds[cond]); }
i should note it's better not use for...in
loop arrays. use $.each()
or for (i=0;i<list.length;i++)
instead.
edit: in option 3, remember switch this.conds[cond]
plain cond
.
Comments
Post a Comment