我有一个包含多列的表格。我有两个选择框:
- 一个用于更改突出显示列的背景颜色
- 一个选择要突出显示的列
这假设我首先点击了#colorselect
选择框。我是否需要先使用 #columnselect
选择框创建另一个函数,然后再在内部构建 #colorselect
函数?
这是我目前所拥有的:
$(function(){
$("#colorselect").change(function() {
$("#colorselect option:selected").each(function() {
if($(this).attr("value")=="red") {
clr="red"
}
if($(this).attr("value")=="green") {
clr="green"
}
if($(this).attr("value")=="") {
clr="yellow"
}
};
$("#columnselect").change(function() {
$("#columnselect option:selected").each(function() {
if($(this).attr("value")=="column1") {
columnhighlightsel="Column1"
}
if($(this).attr("value")=="column2") {
columnhighlightsel="Column2"
}
if($(this).attr("value")=="") {
columnhighlightsel="Column2"
}
}
for (var i = 0; i<= $("#table th").length; i++) {
if($.trim($("#dailytable th:nth-child("+i+")").text()) === columnhighlightsel) {
varcolumnhighlight=i
}
};
$("#table tbody tr td:nth-child("+columnhighlight+")").each(function() {
$(this).css('background-color', clr);
};
最佳答案
我只会编写一个函数来处理任一列中的更改。在执行代码之前检查两者是否为空。那么顺序无关紧要。
然后只需让颜色中的值选择您想要的颜色,并选择列的编号:
$('#colorselect, #columnselect').change(function() {
var $color = $('#colorselect').val(),
$column = $('#columnselect').val();
if ($color && $column) {
$("#table tbody tr td:nth-child("+$column+")").each(function(){
$(this).css('background-color', $color);
};
}
});
根据您的值(value)观,您可能需要调整 if 条件以使其更具体。
关于javascript - 两个选择表列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27321328/