【发布时间】:2016-01-20 04:49:53
【问题描述】:
在这段代码中,它起源于一个带有选择标签的空白表:
<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');
}
});
});
我已经能够简化代码并将所有元素的颜色更改为单一颜色。但是,我正在尝试根据该元素的标题更改每个选择元素的颜色,而不是更改其他元素的背景颜色。
【问题讨论】:
-
请把它放在codepen/fiddle中:jsfiddle.net
-
U 正在尝试使用所选选项更改跨度编码的颜色?
-
@GabrielRodrigues 是的,我正在尝试根据选择更改每个单独的跨度。截至目前,颜色将所有三个选项都变为绿色。
-
@ann0nC0d3r 我可以把整个页面扔到 jsfiddle 中,这只是很多代码。
-
这里是完整的代码:我们正在关注的行在这个小提琴的底部,在 js 行 16364 及以上。 jsfiddle.net/8hknqjax/5
标签: javascript jquery html css