大家好我正在尝试使用我的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的元素添加类弹跳我认为是正确的但它不起作用帮助我。
答案 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
})