[英]Changing the background colour of a given row in a table
我需要根据@ Html.CheckBox中使用的model(boolean)属性的值来更改表中给定行的背景颜色。 使用PostExampleCompleted操作方法中的新复选框值更新模型。
<table>
<thead>
<tr>
<th>Item name</th>
<th>Comments</th>
<th>User</th>
<th>Complete</th>
</tr>
</thead>
<tbody>
<tr id="FooRow">
<td>Foo</td>
<td>@Model.FooComments</td>
<td>@Model.FooUserName</td>
<td>
@using (Ajax.BeginForm("PostFooCompleted", "Home", new AjaxOptions { OnBegin = "ShowProcessingMsg", OnComplete = "HideProcessingMsg" }))
{
@Html.CheckBox("FooItemComplete", Model.FooComplete, new { onClick = "$(this).parent('form:first').submit();" })
}
</td>
</tr>
<tr id="WidgetRow">
<td>Widget</td>
<td>@Model.WidgetComments</td>
<td>@Model.WidgetUserName</td>
@using (Ajax.BeginForm("PostWidgetCompleted", "Home", new AjaxOptions { OnBegin = "ShowProcessingMsg", OnComplete = "HideProcessingMsg" }))
{
@Html.CheckBox("WidgetItemComplete", Model.WidgetComplete, new { onClick = "$(this).parent('form:first').submit();" })
}
</td>
</tr>
</tbody>
</table>
实现这一目标的最佳方法是什么? 代码示例将不胜感激:)。
谢谢。
这样的事情应该可以解决问题,因为我已经理解了你正在努力做的事情。
首先,这是一个css类,如果选中复选框,我会用它来为行着色。
.redBackground
{
background-color: Red;
}
接下来,这里有一些JQuery代码,用于为复选框所在的行着色(如果已选中)。 我还为每个复选框添加了一个“更改”处理程序,因此如果更新它们中的任何一个,就会适当更新行颜色(我刚刚使用红色表示检查复选框的行,并且没有颜色在哪里未选中复选框)。
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(function () {
$('input[type=checkbox]').each(function () {
var checkbox = $(this);
// if the checkbox is already checked, colour its row
CheckStatus(checkbox);
//Every time a check-box status changes we
//want to re-evaluate the row colour
checkbox.change(function () {
CheckStatus(checkbox);
});
});
//Method which checks if the check-box is checked. If it's checked
//the row is given the 'redBackground' class, otherwise it is taken away
function CheckStatus(checkbox) {
if (checkbox.attr('checked') == 'checked') {
checkbox.parent().parent().addClass('redBackground');
}
else {
checkbox.parent().parent().removeClass('redBackground');
}
}
});
</script>
希望这有道理...... :)
代码有点小到完全可以获得您的设置。
从你有一个元素的事实我推断你在表中有多行。 就个人而言,我反对在每一行中都有一个AjaxForm。 这似乎是很多开销。
你可以很容易地拥有一个jQuery代码构造来处理所有行并自己执行必要的任务。
如果你使用jQuery的live函数,你甚至可以独立于添加的行。
复选框或行需要有一个标识符,您可以使用该标识符将ajax调用发送回控制器。 成功后,您可以评估复选框的状态并适当地为行着色。
我将不得不看到更多的代码,真正帮助你。
也许我错过了什么。 这似乎是html或css的工作。 据我所知,有几种方法可以根据您的要求来解决这个问题。
在逐行的基础上(也就是说,你永远不会知道颜色是什么,直到它们被应用程序定义在某个地方或在数据库中静态存储它们的值不是一个选项),分配html样式属性<tr style='background-color: @Model.Colour'>
在行<tr style='background-color: @Model.Colour'>
background-color
设置为您想要的颜色。
在类型/状态的基础上(即,你知道颜色将提前是什么,但不知道它们将被分配给哪些行),我将为每一行定义一个类: <tr class='@Model.Type'>
然后在CSS类中指定background-color
,其名称与Model.Type中的值相同。
要获得该颜色/类型本身,您将要使用您的模型传递它。 您可能已经在您的模型上拥有该属性,我不知道。
对于简单的交替模式, 只需使用此技术或:nth-child(odd)
和:nth-child(even)
css选择器。
有时最简单的解决方案是最佳解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.