[英]How to highlight a table row upon hover conditionally based on table cell values with CSS and jQuery?
So I have an HTML table populated with negative and positive values. 因此,我有一个包含负值和正值的HTML表。 I want to query the specific values and then upon hovering over the table values less than 0 I want to highlight the row with a red background color and for values greater than or equal to 0 should highlight with a blue background.
我想查询特定的值,然后将鼠标悬停在小于0的表值上时,我想用红色背景色突出显示该行,对于大于或等于0的值应该用蓝色背景突出显示。
My current attempt is: 我目前的尝试是:
$(document).ready(function(){
var rows = $("#htmlTable").find('tbody').find('tr');
$.each(rows, function(key, value){
var rowData = $(rows[key]).find('td:eq(1)').html();
if (rowData < 0) {
$("tr").hover(function(){
$(this).addClass('.table-style-1 tbody > tr:hover');
}
}
else {
$("tr").hover(function(){
$(this).addClass('.table-style-2 tbody > tr:hover');
});
}
});
});
The CSS classes are as follows: CSS类如下:
.table-style-1 tbody > tr:hover {
background-color: red;
}
.table-style-2 tbody > tr:hover {
background-color: blue;
}
My above code is correctly getting the data from the table as can been seen with a simple console.log(rowData)
line so I am assuming that my problem is with my implementation of addClass()
and hover()
functions. 我上面的代码可以正确地从表中获取数据,就像通过简单的
console.log(rowData)
行可以看到的那样,因此我假设我的问题出在我的addClass()
和hover()
函数实现上。 The console isn't showing any syntax errors but the table has no highlight functionality upon hovering. 控制台没有显示任何语法错误,但是该表在悬停时没有突出显示功能。 Any help would be greatly appreciated.
任何帮助将不胜感激。
Since you're getting a string with rowData = $(rows[key]).find('td:eq(1)').html();
由于您获得的字符串具有
rowData = $(rows[key]).find('td:eq(1)').html();
you shoud cast the value into an integer when you do a comparison, eg 在进行比较时,应将值转换为整数,例如
if (parseInt(rowData, 10) < 0) { ...
Also why exactly are you adding a class like .table-style-2 tbody > tr:hover
? 另外,为什么还要添加
.table-style-2 tbody > tr:hover
类的类呢? You should just add the a class to the rows eg negative
or positive
(note: you need to use $(this)
and not $('tr')
) 您应该只将a类添加到行中,例如
negative
或positive
(请注意:您需要使用$(this)
而不是$('tr')
)
if (parseInt(rowData, 10) < 0) {
$(this).addClass('negative');
}
else {
$(this).addClass('positive');
}
and define your css like so 像这样定义你的css
tr.negative:hover {
background-color: red;
}
tr.positive:hover {
background-color: blue;
}
here is an example: http://jsfiddle.net/wgkf4o9j/ 这是一个示例: http : //jsfiddle.net/wgkf4o9j/
$(document).ready(function(){
$('table').on('mouseover','tr',function(event){
var $tr = $(event.currentTarget);
$tr.parents('table').find('td').removeClass('blue red');
var value = parseInt($tr.find('td:eq(1)').html());
$tr.find('td').addClass(value < 0?'red':'blue');
})
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.