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

标签 javascript jquery oop

我无法弄清楚这个:

我有一个函数,例如

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

var foo = new test();

单击时会发出“未定义”警报。怎么了?请帮忙。

最佳答案

.click() 中,this 指的是单击的项目。因此,上下文与设置评级时的上下文不同。这两个 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();

Try it out with this jsFiddle

关于Javascript:对象的 this.var 在 jQuery 方法中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3973558/

相关文章:

javascript - 使用按钮而不是文本输入时,更改事件上的 jQuery Datepicker 不会被触发

c++ - 使用 while 循环检查 switch case 中的输入错误

python - 字典类未初始化

c# - 当基类型列表包含基类和接口(interface)时,基类必须在列表中排在第一位

javascript - 在 Angular 中防止从子元素到父元素的 ng-click 传播

javascript - 针对 DocumentFragment 的 XPath 查询

javascript - 倍数上的按钮切换文本

javascript - CoffeeScript 的编译方式不同

javascript - 替换 jQuery 中特定类的图像标题属性

jquery - 在可拖动的 DIV 中添加图像按钮并在单击时切换图像源