Javascript:对象是jQuery方法中的this.var

mvb*_*fst 2 javascript oop jquery

我无法想出这个:

我有一个功能,例如

function test () {
  this.rating = 0;
  $j('#star_rating a').click(function() {
    alert(this.rating);
  });
}

var foo = new test();

点击它会提醒"未定义".怎么了?请帮忙.

Pet*_*tai 5

里面.click()this指单击的项目.所以上下文与你设置的不同rating.那两个this是不同的.

你需要以某种方式保存上下文.

此外,您可能希望return false;或者event.preventDefault()如果您单击某个链接,并且您不希望该页面刷新

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();
Run Code Online (Sandbox Code Playgroud)

尝试使用这个jsFiddle