【问题标题】:Add class using data attribute value while document ready在文档准备好时使用数据属性值添加类
【发布时间】:2014-03-19 20:05:42
【问题描述】:

大家好,我正在尝试为我的 html 使用数据属性,因为我会在加载页面时添加类 这是我的 Jquery

var $this = $(this);
$(document).ready(function(){
    $("[data-load-animation]").each(function() {
        $this.hide();
        var cls = $this.attr("data-load-animation");
        console.log("console: "+cls);
        $this.addClass(cls);    
    })
})

这里是我的Fiddle

我需要为具有此数据属性的每个元素添加类反弹,我认为这是正确的,但它不起作用帮助我。

【问题讨论】:

标签: jquery html5-data


【解决方案1】:

问题似乎是$this 引用,在您的情况下,它指的是window 对象。

您需要引用当前的[data-load-animation] 元素,因此在each() 循环中定义它

$(document).ready(function () {
    $("[data-load-animation]").each(function () {
        var $this = $(this);
        $this.hide();
        var cls = $this.data("loadAnimation");
        console.log("console: " + cls);
        $this.addClass(cls);
    })
})

【讨论】:

    【解决方案2】:

    你放错了$this 尝试以下,其中开头的$this 是指当前窗口

    $("[data-load-animation]").each(function () {
        $this.hide();
        var cls = $(this).data("load-animation"); // Use data instead attr
        console.log("console: " + cls);
        $(this).addClass(cls); // Change to $(this) instead $this
    })
    

    Fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多