简体   繁体   English

jQuery获取父元素的css background-color值

[英]jQuery get css background-color value of parent element

I want to do something a bit awkward and my pseudo code isn't working, but should explain what I'm trying to do. 我想做一些有点尴尬的事情,我的伪代码不起作用,但应该解释我正在尝试做什么。 I have groups of 4 radio buttons, in 6 separate divs, so 24 radios in total. 我有4个单选按钮组,分为6个独立的div,共有24个无线电。 Each div is a particular background colour. 每个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... 当选择特定div中的单选按钮时,我需要获取所选单选按钮所在的div的颜色,并将其存储在变量中,准备将其应用于下一个将创建的元素...

    $("#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);
});

Any help would be appreciated. 任何帮助,将不胜感激。 :) Thanks. :) 谢谢。

尝试使用closest()来查找DOM树中的下一个匹配元素

var color = $(this).closest("div").css("background-color");
$("#voucher_selection_container input:radio").change(function(){

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

});
$('input:radio').change(function(){
 var backColor = $(this).parent().css("background-color");
});

By using the parent function you'll be able to access the parent div 通过使用父函数,您将能够访问父div

$('radio').click(function(){
  $(this).parent();
});
$("#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); 
});

Try this 尝试这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM