我想动态设置div的背景颜色等于直接进行它的表行的背景颜色。这就是我想我想做的事情:
$(this).next().css('background-color', $(this).css('background-color'));
在此主板上寻找答案时,我找到了this thread。这似乎是对他们有用的答案,但我的工作不起作用。感激地接受任何建议。
修改
对于那些要求了解我正在尝试做什么的人,这里是构建我的表格主体的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,这很好用,但是当发生这种情况时我需要它来获取前一行的颜色。
最后更新 - 非常感谢Jonathan Sampson
以下是最终解决方案,基于以下评论:
$('.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
});
答案 0 :(得分:2)
表行永远不会直接位于div
元素之前 - 这将是无效的表标记。如果你想将tr的背景设置为前面的tr的背景,你可以执行以下操作:
$("tr:eq(1)").css("background-color", function(){
return $(this).prev().css("background-color");
});
或者您可能在div
中有tr
,并且您希望div
与tr
具有相同的背景颜色div
。 {1}}:
$(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);
});
答案 1 :(得分:1)
$(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'));
答案 2 :(得分:1)
var neededBG = $('#children_table tr').css('background-color'); // cache the needed color
$('#children_div').css({backgroundColor: neededBG }); // use of the needed color