Tuesday, 15 January 2013

javascript - How use class methods in jQuery functions? -


I want to make automatic color original changer in my JS

This is my html:

  & lt; Div id = "parent" & gt; & Lt; Div id = "target" & gt; Triget & lt; / Div & gt; & Lt; / Div & gt;   

And here's my JS:

  function ColorBox (target_id, btn) {this.parent = $ ("#" + target_id). Parent); This.color = $ (this.parent) .append ('& lt; div class = "color"> ops  gt;); $ (This.color) .append ('& lt; button class = "change" value = "' + btn + '"> gt;' + btn + '& lt; / button & gt;'); This.ChangeColor = function (elm_id) {$ (this.parent) .css ('background', $ (elm_id) .val ()); Back true; } // My problem started $ ("#" + $ (this PPR) .attr ('id') + ".change"). Tie ('click', function () {// How can I do this here. ColorBox.ChangeColor ($ (this));}); } $ (Document) .ready (function () {ColorBox ('target', 'red');});   

I add some elements to target the parent and when click on change class ColorBox.ChangeColor is clicked on , But in the bound method I can not use the this.ChangeColor .

How can I do this now?

A variable (like self ) to it Assign the scope of the function apart by assigning it. This function will avoid any issue from the variables and reaching the functions within different scope.

Here is a working demo:

Here you can see the code changes made by me:

  function ColorBox (target_id, btn) { Var itself = this; Self.parent = $ ("#" + target_id) Parent (); Self.color = self.parent.append ('& lt; div class = "color"> ops & lt; / div & gt;'); Self.color.append ('

No comments:

Post a Comment