jQuery 使用数据属性设置 Class 的 CSS 样式

jQuery set CSS style of Class by using Data attribute

我有这个元素

<div class="circle-200" data-image="pic1" ></div>
<div class="circle-200" data-image="pic2" ></div>
<div class="circle-200" data-image="pic3" ></div>

页面加载后,我希望数据图像值成为相应圆圈 200 的背景图像 class

是否可以使用 jQuery 做这样的事情?

$('.circle-200').css('background-image', "url('"+$(this).data('img')+"')");

您需要使用.css( propertyName, function )

A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.

另请注意,它应该是 image 而不是 img

$('.circle-200').css('background-image', function() {
    return "url('" + $(this).data('image') + "')");
});

$('.circle-200').css('background-image', function() {
  return "url('" + $(this).data('image') + "')"
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="circle-200" data-image="pic1">pic1</div>
<div class="circle-200" data-image="pic2">pic2</div>
<div class="circle-200" data-image="pic3">pic3</div>