【问题标题】:$(this) in javascriptjavascript 中的 $(this)
【发布时间】: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


【解决方案1】:

文档和示例表明参数scorereadOnly 应该是数字和布尔值,而不是回调函数。你可能想重写你的代码:

$(".rating").each(function() {
    // inside the function, this refers to the .rating element being iterated
    $(this).raty({
        score:    parseFloat($(this).attr('data-rating')), // see note #1
        readOnly: $(this).attr('data-readonly') == "true", // see note #2
        halfShow: true
    });
});
  1. .attr() 返回一个字符串; parseFloat() 函数用于转换字符串,例如"2.5"转入号码2.5
  2. 如果属性值等于"true"== "true" 返回布尔值 true;在所有其他情况下返回 false

参考:

【讨论】:

  • 不是这里给出的一元运算符建议的忠实拥护者,也会违反 jslint 验证。而是像这样投射:Number($(this).attr('data-rating');
猜你喜欢
  • 2015-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-24
  • 2021-10-19
  • 2015-01-24
相关资源
最近更新 更多