javascript - Setting up onclick handlers into for -


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:

  1. use $.each() loop, takes function, , consequently keeps context.
  2. use [].foreach(), similar $.each(), native js. (note: not available in older browsers.)
  3. 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

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -