使用数据属性的值设置背景

7 css jquery html5 css3 html5-data

我有16个不同的section标签.每个section-tag都有一个data-属性来为每个标签设置特定的背景颜色section:

<section data-color="#A3D1B5">
Run Code Online (Sandbox Code Playgroud)

现在我想将此颜色设置为背景.

我已经尝试过的
在这个问题中使用HTML5数据属性的CSS值说答案,应该可以设置颜色,background: attr(data-color);但这对我不起作用...

我看了看jQuery data()但我不知道如何为所有section-tags 设置背景.

任何其他解决方案或提示如何处理这个jQuery data()

A. *_*lff 8

DEMO

$("section").css('background', function () { //or for code's consistency, i'd use background-color instead
    return $(this).data('color')
});
Run Code Online (Sandbox Code Playgroud)

  • 有趣的方法,但没有快速将它与'each`循环比较:http://jsperf.com/each-vs-return1 (3认同)