jQuery / Coffee脚本中的数据属性

时间:2012-02-29 00:58:51

标签: jquery coffeescript

我有以下表单代码:

 <input data-color="orange" id="vote_color_id_2" name="color" type="radio" value="2" />Orange
 <input data-color="blue" id="vote_color_id_3" name="color" type="radio" value="3" />Blue
 <input data-color="green" id="vote_color_id_4" name="color" type="radio" value="4" />Green

我在rails中使用Coffee脚本,现在我只是想提醒数据属性data-color的值。

这是我的咖啡脚本

jQuery ->
    $("input[name='color']").change ->
        color = this.data()
        alert color.color

编译后的jQuery看起来像这样:

(function() {

  jQuery(function() {
    return $("input[name='color']").change(function() {
      var color;
      color = this.data();
      return alert(color.color);
    });
  });

}).call(this);

但我一直收到这个错误?

Uncaught TypeError: Object #<HTMLInputElement> has no method 'data'

1 个答案:

答案 0 :(得分:25)

jQuery ->
    $("input[name='color']").change ->
        color = $(this).data()
        alert color.color

jQuery将this分配给触发回调的元素,但它永远不是jQuery对象。如果你想在它上面调用jQuery方法,你必须包装它。