文档就绪时,使用数据属性值添加类

时间:2014-03-19 12:01:37

标签: jquery html5-data

大家好我正在尝试使用我的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

我需要为每个拥有此数据attr的元素添加类弹跳我认为是正确的但它不起作用帮助我。

2 个答案:

答案 0 :(得分: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);
    })
})

答案 1 :(得分:1)

您错放了$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