3

我正在向 DOM 动态添加几个具有“data_record”类的 div。

我希望每个人在单击时都变成一种颜色,而其他人则变成白色背景。

这是我在成功添加 data_record 元素后执行此操作的代码...

$(document).on('click', ".data_record", function(event) {
    //turn all others white (this DOES NOT work!)
    $('.data_record').css('background','#ffffff');

    //turn the clicked element a different colour (this DOES work!)
    $(this).css('background', '#EDC580');
});

那么如何通过他们的类来定位动态添加的元素呢?

谢谢。

4

3 回答 3

2

尝试使用.css('background-color',value)设置背景颜色:

 $(document).on('click', ".data_record", function(event) {
//turn all others white (this now works!)
    $('.data_record').css('background-color','#ffffff');

//turn the clicked element a different colour (this DOES work!)
    $(this).css('background-color', '#EDC580');
});
于 2014-03-25T12:45:28.553 回答
2

这应该改变background-color

$('.data_record').css('background-color','#ffffff');
于 2014-03-25T12:46:07.817 回答
1
$(document).ready(function(){
   var n=0;
    while(n<10)
    {
        $("body").append("<div class=dataRecord>Height</div>");
        n++;
    }

    $(".dataRecord").on("click",function(event){
        var self=$(this);

         $(".dataRecord").css("color","black");
        self.css("color","white");
    });

试试小提琴 http://jsfiddle.net/sgW77/1/

于 2014-03-25T12:59:07.783 回答