我正在尝试根据选择列表选项更改CSS,我在做什么错? 非常感谢帮助! (我无法更改HTML)
非常感谢。
欧文
$("select").change(function() {
var color = $("#5f01264e722ae").val();
$("#sw_poster_text2").css("background", color);
});
.sw_poster_text2 {
margin: 30px;
background: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wapf-field-input">
<select data-is-required="" data-field-id="5f01264e722ae" name="wapf[field_5f01264e722ae]" class="wapf-input">
<option value="">choose an option</option>
<option value="0z489" data-wapf-label="black">black </option>
<option value="wu4xz" data-wapf-label="brown">brown </option>
<option value="5k848" data-wapf-label="blue">blue </option>
</select>
</div>
<div class="sw_poster_text2">My name</div>
答案 0 :(得分:0)
使用$(this).find('option:selected').data('wapf-label')
获取选择的值,并使用.
而不是#
选择具有特定类的元素。
var color = $(this).find('option:selected').data('wapf-label')
$(".sw_poster_text2").css("background", color);
$("select").change(function() {
var color = $(this).find('option:selected').data('wapf-label')
$(".sw_poster_text2").css("background", color);
});
.sw_poster_text2 {
margin: 30px;
background: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wapf-field-input">
<select data-is-required="" data-field-id="5f01264e722ae" name="wapf[field_5f01264e722ae]" class="wapf-input">
<option value="">choose an option</option>
<option value="0z489" data-wapf-label="black">black </option>
<option value="wu4xz" data-wapf-label="brown">brown </option>
<option value="5k848" data-wapf-label="blue">blue </option>
</select>
</div>
<div class="sw_poster_text2">My name</div>
答案 1 :(得分:-1)
您的选项值不是有效颜色,您需要在设置样式后将有效颜色设置为,
$("select").change(function() {
var color = $("#5f01264e722ae").val();
$("#sw_poster_text2").css("background", color);
});
.sw_poster_text2 {
margin: 30px;
background: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wapf-field-input">
<select data-is-required="" data-field-id="5f01264e722ae" name="wapf[field_5f01264e722ae]" class="wapf-input">
<option value="">choose an option</option>
<option value="black" data-wapf-label="black">black</option>
<option value="brown" data-wapf-label="brown">brown</option>
<option value="blue" data-wapf-label="blue">blue</option>
</select>
</div>
<div class="sw_poster_text2">My name</div>