两个带有表列的选择

Two selects with table columns

本文关键字:选择 两个      更新时间:2023-09-26

我有一个包含多列的表。我有两个选择框:

  • 一个用于更改突出显示列的背景颜色
  • 一个用于选择要突出显示的列

这假设我先单击#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);
    };
  }
});

根据您的值,您可能需要调整 if 条件以使其更具体。

 $("#colorselect").change(function(){
           clr = $("#colorselect option:selected").attr("value");
        clr = clr == '' ? 'yellow' : clr;
        color();
    }
   $("#columnselect").change(function(){
         columnhighlightsel= $(this);
        color();
    }
function color(){
   if(!columnhighlightsel || !clr){
      return;
   }
   columnhighlightsel.css('background-color', clr);
}

现在,您必须将列突出显示和 clr- 变量放入颜色函数上下文中。