我需要根据select中选择的颜色来设置表格行的背景颜色。
我有一些困难,所以我需要帮助。
当我从一个选择中选择颜色时,颜色会应用到每一行,这不是我想要的。 我希望颜色应用于选择颜色的特定行
有人可以帮帮我吗?
HTML:
<table id="color-table">
<tr>
<td>First name</td>
<td>Last name</td>
<td>Address</td>
<td>
<select>
<option value="red">Red</option>
<option value="yellow">yellow</option>
<option value="green">green</option>
</select>
</td>
</tr>
<br />
<tr>
<td>First name</td>
<td>Last name</td>
<td>Address</td>
<td>
<select>
<option value="red">Red</option>
<option value="yellow">yellow</option>
<option value="green">green</option>
</select>
</td>
</tr>
</table>
CSS:
.红色{
background: #ff3333;
}
.yellow{
background: #ffff80;
}
.green{
background: #80ff80;
}
JS:
$("select").on('change', function() {
var sel = $("select").val();
if (sel =='red')
{
$(this).addClass("red");
}
else if (sel == 'yellow')
{
$(this).addClass("yellow");
}
else if (sel == 'green')
{
$(this).addClass("green");
}
});
$('select').change(function () {
$('#color-table').removeClass('red yellow green').addClass(
$(this).find('option:selected').text().toLowerCase()
);
})
.change();
fiddle 在这里:https://jsfiddle.net/lzrnic/9j2cg1qw/
最佳答案
您可以简单地使用选择的值作为类名。
顺便说一句,removeClass()
不带参数将删除所有类。
$("select").on('change', function() {
$(this).closest('tr').removeClass().addClass($(this).val());
}).trigger('change');
.red{
background: #ff3333;
}
.yellow{
background: #ffff80;
}
.green{
background: #80ff80;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="color-table">
<tr>
<td>First name</td>
<td>Last name</td>
<td>Address</td>
<td>
<select>
<option value="red">Red</option>
<option value="yellow">yellow</option>
<option value="green">green</option>
</select>
</td>
</tr>
<br />
<tr>
<td>First name</td>
<td>Last name</td>
<td>Address</td>
<td>
<select>
<option value="red">Red</option>
<option value="yellow">yellow</option>
<option value="green">green</option>
</select>
</td>
</tr>
</table>
关于javascript - 更改表格行的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50162218/