【问题标题】:How to change the css of a dynamically added element?如何更改动态添加元素的css?
【发布时间】:2014-05-03 07:41:12
【问题描述】:

我正在向 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');
});

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

谢谢。

【问题讨论】:

标签: jquery dynamic-html


【解决方案1】:

尝试使用.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');
});

【讨论】:

  • 所以代码是正确的,但“背景”不适用于 jQuery。 Jquery 需要更具体的 css 吗?
  • 在这种情况下为什么 $(this).css('background', '#EDC580');工作吗?
  • @daktau:我无法重现它不工作。你能分享一下小提琴吗?
【解决方案2】:

这应该会改变background-color:

$('.data_record').css('background-color','#ffffff');

【讨论】:

    【解决方案3】:
    $(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/

    【讨论】:

    • 为什么要遍历数据记录? jQuery 自动迭代。 OP也想要背景颜色而不是文本颜色......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-28
    相关资源
    最近更新 更多