gpt4 book ai didi

javascript - jQuery根据标题更改下拉列表元素的背景颜色

转载 作者:太空宇宙 更新时间:2023-11-03 19:57:07 24 4
gpt4 key购买 nike

在这段代码中,它起源于一个带有选择标签的空白表格:

<table class="table">
<tr>
<td>
<select id="e2">
<option value="green">Green</option>
<option value="yellow">Yellow</option>
<option value="red">Red</option>
</select>
</td>
</tr>
</table>

这是使用 jQuery 函数生成的,该函数将选择格式化为嵌套范围列表:

<table class="table">
<tr>
<td>
<b class="tablesaw-cell-label">Status</b>
<span class="tablesaw-cell-content">
<select tabindex="-1" class="select2-hidden-accessible" id="e2" aria-hidden="true">
<option value="green">Green</option>
<option value="yellow">Yellow</option>
<option value="red">Red</option>
</select>
<span class="select2 select2-container select2-container--default select2-container--below" style="width: 64px;" dir="ltr">
<span class="selection">
<span tabindex="0" class="select2-selection select2-selection--single" role="combobox" aria-expanded="false" aria-haspopup="true" aria-labelledby="select2-e2-container">
<span title="Green" class="select2-selection__rendered" id="select2-e2-container">Green</span>
<span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span>
</span>
</span>
<span class="dropdown-wrapper" aria-hidden="true"></span>
</span>
</span>
</td>
</tr>
</table>

我试图在加载页面后根据元素的标题使用 jQuery 更改颜色。这是我当前的颜色变化功能。这在 select2 函数创建并格式化下拉列表后运行。

$(document).ready(function () {
$('#e1').select2();
$('#e2').select2();

$('.select2-selection.select2-selection--single span.select2-selection__rendered').each(function () {
var title = $(this).attr('title');
console.log(title);
if (title === 'Green') {
$(this).parent().css('background-color', 'green');
}
if (title === 'Yellow') {
$(this).parent().css('background-color', 'yellow');
}
if (title === 'Red') {
$(this).parent().css('background-color', 'red');
}
});
});

我已经能够简化代码并将所有元素的颜色更改为单一颜色。但是,我试图根据每个选择元素的标题更改该元素的颜色,而不更改其他元素的背景颜色。

最佳答案

根据您已删除的其他帖子,我认为这就是您所追求的:

$(document).ready(function () {
$('#e1').select2();
$('#e2').select2().on('change', function(){
$(this).next().find('.select2-selection').css({
backgroundColor: this.value
});
}).trigger('change');
});

只需监听更改事件,然后更新 CSS。

这是来自您的另一篇文章的更新 fiddle :https://jsfiddle.net/jmarikle/ea7q41k7/

关于javascript - jQuery根据标题更改下拉列表元素的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34882354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com