data-*每个类的值

use*_*062 0 html javascript css jquery

我有2个div

<div class='class' data-color='gray'>
</div>

<div class='class' data-color='red'>
</div>
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,data-color两者都有不同的值.第一个存在gray,第二个存在red.

这是我在JavaScript(jQuery)中使用它所做的:

$(".class").each(function(){
    var DivDataColor = $(".class").data("color");
    $(this).css({'background': DivDataColor});
});
Run Code Online (Sandbox Code Playgroud)

这使得它们都具有灰色,我认为正在发生的是它只是采用第一个div的数据类型然后将其应用于两者.

所以对于trys我把变量放在.each()函数之外

var DivDataColor = $(".class").data("color");
$(".class").each(function(){
    $(this).css({'background': DivDataColor});
});
Run Code Online (Sandbox Code Playgroud)

但我仍然没有运气,可能是什么工作?

Lig*_*ica 6

$(".class").each(function(){
    var DivDataColor = $(".class").data("color");
    //                 ^^^^^^^^^^^
    $(this).css({'background': DivDataColor});
});
Run Code Online (Sandbox Code Playgroud)

在这里,您将重新选择所有匹配元素.然后,因为只能有一个"data-color"值,是的,第一个正在被使用.

使用$(this),如下所示:

$(".class").each(function() {
    var $this = $(this);
    var DivDataColor = $this.data("color");
    $this.css({'background': DivDataColor});
});
Run Code Online (Sandbox Code Playgroud)

或者,最好的是,通过采用相反的方法将操作合并为一个:

$(".class").css("background", function() {
    return $(this).data("color");
});
Run Code Online (Sandbox Code Playgroud)