jquery - Javascript scope of object property -


let's want make javascript class boxes in page. when object of class made, want add click event require me accessing 1 or many of unique properties. how that? here's example:

function box(boxclassname, originalcolor, changecolor){  this.boxclassname = boxclassname; this.originalcolor = originalcolor; this.changecolor = changecolor;  this.initialize = function (){      var html = '<div class="' + this.boxclassname + '></div>';      $(document).append(html);     $(this.boxclassname).css("background-color", originalcolor);      // toggle box color on click     $(this.boxclassname).click(function (){         // this.boxclassname undefined here, none of works          if ($("." + this.boxclassname).css("background-color") == originalcolor) {             $("." + this.boxclassname).css("background-color", this.changecolor);         } else {             $("." + this.boxclassname).css("background-color", this.originalcolor);         }     }); };  this.initialize();  } 

there 2 ways:

1) keep reference in variable , use that:

// toggle box color on click var self = this; $(this.boxclassname).click(function () {     if ($("." + self.boxclassname).css("background-color") == originalcolor) {         $("." + self.boxclassname).css("background-color", self.changecolor);     } else {         $("." + self.boxclassname).css("background-color", self.originalcolor);     } }); 

2) or bind click callback box

$(this.boxclassname).click(function () {     if ($("." + this.boxclassname).css("background-color") == originalcolor) {         $("." + this.boxclassname).css("background-color", this.changecolor);     } else {         $("." + this.boxclassname).css("background-color", this.originalcolor);     } }.bind(this)); 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -