【发布时间】:2012-06-22 07:43:04
【问题描述】:
我在 js 中使用 this 时遇到问题。我有一个像这样使用this 的函数:
var refreshRequesterStar = function() {
$(".rating").raty({
score: function() { return $(this).attr('data-rating'); },
readOnly: function() { return $(this).attr('data-readonly'); },
halfShow: true
});
};
评分div如下:
<div class="rating" data-readonly="false" data-rating="3.0" style="cursor: default; width: 100px;" title="not rated yet">
<div class="rating" data-readonly="false" data-rating="0.0" style="cursor: default; width: 100px;" title="not rated yet">
这是由这个函数调用的:
$("body").ajaxComplete(function(){
refreshRequesterStar();
$(".time_to_expire").each(function(){
setCountDown(this);
})
$('select').chosen();
});
我可以设置 score 值,但无法设置 readOnly 值。当我使用firebug进行调试时,我发现第一个this指向了div,第二个this指向了window。我哪里错了?注意:我对 JavaScript 了解不多。
更多信息:我在 rails 中使用了 raty http://www.wbotelhos.com/raty。
【问题讨论】:
-
顺便说一句,这不是纯 JavaScript。从
$的外观和使用来看,我会说它是jQuery。尽管如此,this 和 scope 在 JS 中是一件棘手的事情,尤其是对于具有更传统背景的程序员来说 -
实际上是 jQuery。对不起,我没有添加 jquery 标签。既然是jquery,我不认为这个问题是重复的。
-
这里有 data-readOnly 而不是 data-readonly: return $(this).attr('data-readOnly');并且该属性是数据只读的。看看吧!
-
不提供这个作为答案,因为我不确定而且我的 jQuery 生锈了......但
.attr('data-readOnly')不应该匹配data-readonly="false"(不同大小写的o)?
标签: javascript jquery ruby-on-rails-3 raty