从上一个 span 元素中获取样式

Get style from previous span element

本文关键字:获取 样式 元素 上一个 span      更新时间:2023-09-26

使用 jquery,我想从被点击的 spzn 之前获取 rgb 颜色代码。

我可以通过以下方式获得点击:

$(document).ready(function(){
  $( "#myDiv :radio").click(function(){
    alert("Got here");
    });
});

那么,如何在单选按钮之前从具有类 swatchColour_1 的跨度中获取 rgb 代码 #000000。

大约有30种不同颜色的li元素。我实际可以更改的唯一代码是第一个带有 id="myList" 的div

<div class="productAttributeList" id="myList" style="">
    <div class="productAttributeRow xx" id="ffb492067dcd98c19b6be89e9230f4fc">
        <div class="productAttributeLabel">
            <label for="06b0854950dd6cc1d296718965c0d36a">
                <span class="required">*</span>
                    <span class="name">Color choice:</span>
            </label>
        </div>
        <div class="productAttributeValue">
            <div class="productOptionPickListSwatch">
                <ul>
                    <li class="swatch hasPreview swatchOneColour">
                        <label for="0780a439a3a2ec8492a8772f4f5d739a">
                        <span class="previewContent">
                            <span class="swatchColours swatchOneColour showPreview" title="Black - 070">
                                <span class="swatchColour swatchColour_1" style="background-color:#000000;">&nbsp;</span>
                                </span>
                            </span>
                            <input type="radio" class="validation" name="attribute[119]" value="195" id="0780a439a3a2ec8492a8772f4f5d739a"  />
                            <span class="name">Black - 070</span>
                        </label>
                    </li>

...

谢谢加里

$(document).ready(function(){
  $( "#myDiv :radio").click(function(){
    alert($(this).prev("span.previewContent").find(".swatchColour_1").css("background-color"));
    });
});

您可以使用.prev().find().css()方法:

$( "#myList input[type=radio]").change(function() {
    var color = $(this).prev().find('.swatchColour_1').css('background-color');
});

或使用.closest()方法:

var color = $(this).closest('.previewContent')
                   .find('.swatchColour_1')
                   .css('background-color');

http://api.jquery.com/