高亮显示条带HTML表中单击的行
Highlighting the clicked row of a striped HTML table
下面是我在jsFiddle上的一个问题示例。
我有一个表,通过在CSS中使用tr:nth-child(odd)
强制使用带条纹的行,就像在Twitter Bootstrap中为table-striped
类所做的那样。我想突出显示该表中最近单击的行。我使用以下Javascript来实现这一点:
$('#mytable tbody tr').live('click', function(event) {
$clicked_tr = $(this);
$clicked_tr.parent().children().each(function() {
$(this).removeClass('highlight')
});
$clicked_tr.addClass('highlight');
});
该代码在没有条纹行的表中运行良好。但是对于条纹行,highlight
类的背景颜色不会覆盖table-striped
类的背景色。为什么?我该如何让它发挥作用?
http://jsfiddle.net/iambriansreed/xu2AH/9/
.表条纹类
.table-striped tbody tr.highlight td { background-color: red; }
和清洁jQuery:
$('#mytable tbody tr').live('click', function(event) {
$(this).addClass('highlight').siblings().removeClass('highlight');
});
更新:.live()
已被弃用。使用.on()
。
$('#mytable').on('click', 'tbody tr', function(event) {
$(this).addClass('highlight').siblings().removeClass('highlight');
});
已修复:http://jsfiddle.net/iambriansreed/xu2AH/127/
增加.highlight
的特异性
阅读本文并查看此答案中的演示,了解更多"CSS特异性"
//your normal green has "023"
//.table-striped 010
//tbody 001
//tr 001
//:nth-child(odd) 010
//td 001 = 023
.table-striped tbody tr:nth-child(odd) td {
background-color: green;
}
// your highlight only has "010"
//thus it can't take precedence over the applied style
.highlight{
background-color: red
}
//a more specific highlight = "033" will take precedence now
//.table-striped 010
//tbody 001
//tr 001 everything is about the same except
//.highlight 010 <-- an added class can boost specificity
//:nth-child(odd) 010
//td 001 = 033
.table-striped tbody tr.highlight:nth-child(odd) td {
background-color: red;
}
这要容易得多,只需使用de Bootstrap css类(如.info.warning.error或.success)即可在选定行和未选定行之间切换。他们拥有这场争吵的所有州。
我使用了这个,基于@iambriansreed的回答:
$('#mytable tbody tr').live('click', function(event) {
$(this).addClass('info').siblings().removeClass('info');
}
只需将Bootstrap .table-striped
CSS类编辑为:
.table-striped tbody tr:nth-child(odd),
.table-striped tbody tr:nth-child(odd) th {
background-color: #f9f9f9;
}
.table-striped tbody tr:nth-child(even){
background-color: yellow;
}
删除所有您不想要的td样式。然后它就起作用了。
当您单击行时,还应应用此样式:
.selected { background-color:#2f96b4 !important; }
如果没有!important
,它将无法工作。
据我所知:
$('#mytable tbody tr').live('click', function(event) {
$clicked_tr = $(this);
$('#mytable tbody tr').removeClass("highlight");
$clicked_tr.addClass('highlight');
});
相关文章:
- 如何通过单击html按钮获得h1的文本值
- 单击HTML展开框
- Javascript 单击html字段值而不编辑.js文件
- 提交表单的可能性(左-/中-/在新选项卡或窗口中打开-)单击html链接
- 如何在单击asp.net按钮时自动单击html按钮
- 如何通过单击HTML中的按钮关闭当前选项卡
- 如何在Windows phone 8.0应用程序的WebBrowser中自动单击html按钮
- 只想在用户单击 html 表单上的“提交”时显示绿色复选标记
- 是否有可能通过单击html页面上的按钮在我的Web服务器上运行c ++程序
- 如何显示uI-select(angularjs)时,单击html元素
- 单击 HTML 子菜单时显示
- addEventListner 在单击 HTML 之前触发
- 反应:仅在单击 html 元素时执行一次操作
- 如何通过单击 html 页面中的菜单从 jsp 调用 java 方法
- 使用 JavaScript 单击 HTML 中的链接
- 通过单击html按钮发送电子邮件
- 单击“HTML 计数器”按钮
- 原生脚本中的动态抓取?需要抓取页面,能够单击HTML按钮
- 如何检测是否单击 Html 画布的某个区域
- 通过单击HTML链接在谷歌地图上显示信息窗口