我无法弄清楚这个:
我有一个函数,例如
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/