将颜色应用于select w/jQuery上的行
如果我有一个带有下拉选项的选择器,如何在更改时更改此行中所有单元格的颜色将颜色应用于select w/jQuery上的行,jquery,Jquery,如果我有一个带有下拉选项的选择器,如何在更改时更改此行中所有单元格的颜色 function changeColor(){ } $(".mySelector").change(function() { changeColor(); }); <table> <tr> <td>val 1</td> <td>val 2</td> <td> <select class="
function changeColor(){
}
$(".mySelector").change(function() {
changeColor();
});
<table>
<tr>
<td>val 1</td>
<td>val 2</td>
<td>
<select class="mySelector">
<option value="red">red</option>
<option value="grn">green</option>
<option value="blu">blue</option>
</select>
</td>
</tr>
<tr>
<td>val 3</td>
<td>val 4</td>
<td>
<select class="mySelector">
<option value="red">red</option>
<option value="grn">green</option>
<option value="blu">blue</option>
</select>
</td>
</tr>
</table>
函数changeColor(){
}
$(“.mySelector”).change(函数(){
变色();
});
瓦尔1
val 2
红色
绿色
蓝色
val 3
val 4
红色
绿色
蓝色
您可以使用获取您的
元素最近的
祖先:
$(".mySelector").change(function() {
$(this).closest("tr").css("background-color",
$("option:selected", this).text());
});
您应该将选项值更改为有效颜色,而不是缩写,然后可以执行以下操作:
<option value="red">red</option>
<option value="green">green</option>
<option value="blue">blue</option>
JSFiddle:
如果要确保在初始化时设置颜色,可以链接另一个change
调用:
$(".mySelector").change(function() {
$(this).closest("tr").css("background-color", this.value);
}).change(); //Set background color without needing to change the selected option.
$(".mySelector").change(function() {
$(this).closest("tr").css("background-color", this.value);
}).change(); //Set background color without needing to change the selected option.