문제

I'm trying to use data attributes for my HTML. I want to add a class while loading the page.

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);    
    })
})

Here is my JSFiddle Demo

I need to add a class bounce for every element having this data attribute, I think... but I'm not sure why it's not working.

도움이 되었습니까?

해결책

The problem seems to be the $this reference, in your case it is referring the window object.

Instead you need to refer the current [data-load-animation] element, so define it within the each() loop

$(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);
    })
})

다른 팁

You are misplacing $this Try with the following, Where $this in the starting refers to current window

$("[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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top