I can't figure this one out:
I have a function, e.g.
function test () {
this.rating = 0;
$j('#star_rating a').click(function() {
alert(this.rating);
});
}
var foo = new test();
On click it alerts "undefined". What is wrong? Please help.
Inside the .click() the this refers to the item clicked. So the context is different than when you set rating. Those two thiss are different.
You need to conserve the context somehow.
Also, you may want to return false; or event.preventDefault() if you are clicking on a link and you don't want the page to refresh
function test () {
this.rating = 0;
var oldThis = this; // Conserving the context for use inside .click()
$j('#star_rating a').click(function() {
alert(oldThis.rating);
return false; // Use this if you don't want the page to change / refresh
});
}
var foo = new test();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With