jQuery,将表元素的背景色设置为前一个元素的颜色



我想动态地将div 的背景颜色设置为等于直接进行它的表格行的背景颜色。以下是我认为我想做的:

$(this).next().css('background-color', $(this).css('background-color'));

在这个板上寻找答案时,我发现了这个线程。这似乎是对他们有用的答案,但我的答案不起作用。任何建议都感激地接受。

编辑

对于那些要求看看我想要做什么的人,这里是构建我的表正文的 PHP 代码:

<?php
//  For every row past the first (header) row, create a table entry
    while ( $row = fgetcsv($handle) ) {
        echo "<tr class='c_edd_row'>";                      
        //  Build each cell         
        $num = count($row);         
        for ($c=0; $c < $num; $c++) {
            //  Do not echo entries 23 through 27 (unused cells)
           if ( $c < 23 || $c > 27 ) {
              echo "<td>".$row[$c]."</td>";
              //  save the last entry for the hidden div
              $validation_notes = $row[$c];
          }
        }
        echo "</tr>";
        echo "<tr class='c_sub_row'>
        <td colspan='42' class='c_notes_div'>
        <div class='c_notes_div'>".$validation_notes."</div>
        </td></tr>";
    }
?>

响应者是正确的,我没有很好地陈述我的问题。我所说的div 实际上包含在 TR 中。我将其用作最后一行条目中数据的每一行的下拉列表。

当我单击一行时,具有类 c_sub_row 的以下行从 display:none 更改为 display:table-row,这很好用,但发生这种情况时我需要它采用前行的颜色。

最终更新 - 非常感谢乔纳森·桑普森

根据以下评论,这是最终解决方案:

$('.c_edd_row').on('click',  function(event) {
    var bg = $(this).css("background-color");
    $(this).next().css("background-color", bg);   //  colors the next row
    $(this).next().find('div').css("background-color", bg);  //  colors the div
});

表行从不直接位于div元素之前 - 这将是无效的表标记。如果要将 tr 的背景设置为前面的 tr 的背景,可以执行以下操作:

$("tr:eq(1)").css("background-color", function(){
  return $(this).prev().css("background-color");
});

或者,您可能在tr中有一个div,并且您希望div具有与divtr相同的背景颜色:

$(this).css("background-color", function(){
  return $(this).closest("tr").prev().css("background-color");
});

其中this是当前div元素。

这里的魔力发生在用作$.css方法的第二个参数的匿名函数中。从它内部,你几乎可以做任何事情。例如,我们可以挑选页面上的任何其他元素并复制其背景颜色:

$(this).css("background-color", function(){
  return $(".someOtherDiv").css("background-color");
});

同样,假设this是我们的目标div元素,它现在将具有与<div class="someOtherDiv">...</div>相同的背景颜色。

更新

从评论中,听起来您有两行表格(至少(。一个可见,下一个隐藏。在第二个中,你有一个div。单击第一个(可见(表行时,您希望既显示第二个,又希望将第一个 TR 的 bg 应用于第二个(现在可见(表行中的 DIV:

$("tr:visible").on("click", function(event){
  var bg = $(this).css("background-color");
  $(this).next().show().find("div").css("background-color", bg);
});
$(document).ready(function(){
 $(".your_table_class tr:last-child").each(function(){
    $(this).parent().next().css('background-color', $(this).css('background-color'));
 })
});

这里.your_table_class是用于所有表中使用的类/虚拟类,其下一个div 将被着色。请记住,div 应该是表的下一个元素。

此外,如果您的表包含<tbody>标签,则该行将$(this).parent().parent().next().css('background-color', $(this).css('background-color'));

jsBin demo

var neededBG = $('#children_table tr').css('background-color');   // cache the needed color
$('#children_div').css({backgroundColor: neededBG });             // use of the needed color

最新更新