gpt4 book ai didi

jquery - 如何更改特定行中所有 select2 元素的颜色

转载 作者:行者123 更新时间:2023-11-28 15:23:19 25 4
gpt4 key购买 nike

我正在使用 select2,但我想更改表格中所有选择元素的背景颜色。但是,我正在运行的 jQuery 代码只更改了第一个选择输入的颜色。有解决此问题的提示吗?

我的 html 看起来像

<table width="100%" class="table table-striped table-bordered table-hover" id="TB2">
<thead>
<tr>
<th>Name</th>
<th>Type of Student</th>
<th>Thesis/ Project/ Research</th>
</tr>
</thead>
<tbody>
<tr class="table_row">
<td><input class="form-control alert-danger" type="text" name="a"/></td>
<td><select class="form-control alert-danger"">
<option value="">Type</option>
<option>Bachelors</option>
<option>Masters</option>
<option>Doctoral</option>
<option>Postdoctoral</option>
</select></td>
<td><select class="form-control">
<option value="">Select</option>
<option>Thesis</option>
<option>Project</option>
<option>Research</option>
</select></td>
</tr>
</tbody>
</table>

我的 JQuery 代码如下所示:

$(document).ready(function () {
$('select').select2({
placeholder: "Select",
allowClear: true
});
$('#TB2 tbody tr').find("select").data("select2").$container.find('.select2-selection').css("background-color", "rgb(10,10,10)");
});

jQuery 成功地使第一个 select 语句具有适当的背景,但不影响第二个。我需要使整行中的所有选择元素都具有 RGB(10,10,10) 的背景。我在页面的其他部分也有其他选择输入,我不想影响背景,所以我只需要影响 tr。

最佳答案

您的问题在这一行:

$('#TB2 tbody tr').find("select").data("select2").......

.data("select2")仅返回第一个值,而不返回要更改背景颜色的元素数组。

您可以使用 .each()迭代每个选择标签。

$('#TB2 tbody tr').find("select").each(function(idx, ele) {
$(ele).data("select2").$container.find('.select2-selection')
.css("background-color", "rgb(10,10,10)");
});

片段:

$('select').select2({
placeholder: "Select",
allowClear: true
});
$('#TB2 tbody tr').find("select").each(function(idx, ele) {
$(ele).data("select2").$container.find('.select2-selection')
.css("background-color", "rgb(10,10,10)");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>


<table width="100%" class="table table-striped table-bordered table-hover" id="TB2">
<thead>
<tr>
<th>Name</th>
<th>Type of Student</th>
<th>Thesis/ Project/ Research</th>
</tr>
</thead>
<tbody>
<tr class="table_row">
<td><input class="form-control alert-danger" type="text" name="a"/></td>
<td><select class="form-control alert-danger"">
<option value="">Type</option>
<option>Bachelors</option>
<option>Masters</option>
<option>Doctoral</option>
<option>Postdoctoral</option>
</select></td>
<td><select class="form-control">
<option value="">Select</option>
<option>Thesis</option>
<option>Project</option>
<option>Research</option>
</select></td>
</tr>
</tbody>
</table>

关于jquery - 如何更改特定行中所有 select2 元素的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45680874/

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