【问题标题】:Data attributes in jQuery/Coffee scriptjQuery/Coffee 脚本中的数据属性
【发布时间】:2012-03-18 12:41:05
【问题描述】:

我的表单代码如下:

 <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'

【问题讨论】:

    标签: jquery coffeescript


    【解决方案1】:
    jQuery ->
        $("input[name='color']").change ->
            color = $(this).data()
            alert color.color
    

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

    【讨论】:

      猜你喜欢
      • 2016-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-27
      相关资源
      最近更新 更多