我在使用 jQuery/CSS/data 属性设置背景时遇到问题。我没有正确地重构代码,可能会找到更好的解决方案,但想找出为什么这不起作用......解释起来有点困难......见下文
$('.promoCarousel').find('.image').each(function(){
$(this).css({
'background-image': $(this).attr('data-mob-src'), // DOESNT SET BACKGROUND IMAGE
'width' : 288,
'height' : 288
})
$(this).addClass("mobview");
});
是因为我将 $(this) 与 $(this) 一起使用吗??
最佳答案
将 $(this)
设置为局部变量并引用它。
无论如何,当多次调用 $(this)
时,您都应该这样做,因为它更有利于从局部变量读取性能。
另外,我的猜测是您没有在 data-mob-src
属性值中包含 url()
。我建议将其连接起来,如下例所示:
$('.promoCarousel').find('.image').each(function(){
var $this = $(this);
$this.css({
'background-image': 'url(' + $this.attr('data-mob-src') + ')',
'width' : 288,
'height' : 288
})
$this.addClass("mobview");
});
关于javascript - 以对象格式设置 css 时使用 $(this) 和数据 attr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17046919/