【问题标题】:Two selects with table columns带有表格列的两个选择
【发布时间】:2014-12-05 17:18:37
【问题描述】:

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

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

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

【问题讨论】:

  • 您能发布您的 HTML 吗?据推测,除非您有“默认”列,否则您需要先选择列,然后再更改列颜色...
  • 没有得到您的问题,但是您应该像这样关闭 jquery 更改功能 });而不是这样 };
  • 检查更新后的问题,您严重遗漏了关闭}) 问题。
  • 糟糕!谢谢静默。
  • 欢迎来到 StackOverflow!请参阅"Should questions include “tags” in their titles?",其中的共识是“不,他们不应该”。

标签: javascript jquery html css multiple-columns


【解决方案1】:

我只想编写一个函数来处理任一列中的更改。在执行代码之前检查是否为空。那么顺序无关紧要。

然后只需让你的颜色中的值选择你想要的颜色,列就是列的编号:

$('#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 条件调整为更具体。

【讨论】:

  • 谢谢!这很有帮助。我知道我让这变得比现在更复杂。
【解决方案2】:
 $("#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);
}

您现在必须将 columnhighlightsel 和 clr- 变量放入颜色函数上下文中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多