【问题标题】:jQuery get css background-color value of parent elementjQuery获取父元素的css背景颜色值
【发布时间】:2026-01-13 01:55:02
【问题描述】:

我想做一些有点尴尬的事情,我的伪代码不起作用,但应该解释一下我想要做什么。我有 4 个单选按钮组,在 6 个单独的 div 中,所以总共有 24 个单选按钮。每个 div 都是特定的背景颜色。 When a radio button within a particular div is selected, I need to grab the colour of the div the selected radio button is within, and have it stored in a variable ready to apply it to an element that'll be created next...

    $("#voucher_selection_container input:radio").change(function(){
    //var color = $(this).parent("div").css("background-color");
    //alert(color);
    $("#voucher_customisation_container").slideDown(600);
    //$("#voucher_customisation_container .voucher_box").css("background-color", color);
});

任何帮助将不胜感激。 :) 谢谢。

【问题讨论】:

标签: jquery html css dom


【解决方案1】:

尝试closest() 查找 DOM 树上的下一个匹配元素

var color = $(this).closest("div").css("background-color");

【讨论】:

  • 嗨,你是对的。 Parent 会给我一个字段集,我需要 parent().parent(),显然这是不对的,最接近的工作完美。谢谢。
  • 请注意,您也可以使用 .parents('div')
  • @Toni parents('div') 会让你成为 div 的所有父母
  • 我明白了,但是 .closest 有可能返回一个孩子,不是吗?我会为 div 应用一个类来确保。那么 parents('.class') 不应该失败
  • 不,最接近的只在 DOM 树上查找最接近的位置,而不是向下。
【解决方案2】:
$("#voucher_selection_container input:radio").change(function(){

     var color = $(this).parent("div").css("backgroundColor");

});

【讨论】:

    【解决方案3】:
    $('input:radio').change(function(){
     var backColor = $(this).parent().css("background-color");
    });
    

    【讨论】:

      【解决方案4】:

      通过使用 parent 函数,您将能够访问父 div

      $('radio').click(function(){
        $(this).parent();
      });
      

      【讨论】:

        【解决方案5】:
        $("#voucher_selection_container input:radio").change(function(){
            var color = $(this).parent().css("background-color");
            alert(color);
            //$("#voucher_customisation_container").slideDown(600);
            $("#voucher_customisation_container .voucher_box").css("background-color", color); 
        });
        

        试试这个

        【讨论】: