简体   繁体   English

Javascript来检查是否 <td> 具有特定的背景颜色

[英]Javascript to check if <td> is of a particular background colour

Just getting to grips with javascript and jquery 刚刚掌握javascript和jquery

I am setting backgroundColor of a table cell based on its value. 我根据其值设置表格单元格的backgroundColor

 $("td.ms-vb2").filter(function(index){return $(this).text() === "Yes";}).css("backgroundColor", "#81F79F");
 $("td.ms-vb2").filter(function(index){return $(this).text() === "No";}).css("backgroundColor", "#FE642E");

Could someone tell me how I would be able write an if-else statement where if the color is #81F79F do an alert and if the color is #FE642E , do another alert 有人能告诉我怎么能写一个if-else语句,如果颜色是#81F79F做一个警报,如果颜色是#FE642E ,再做一个警告

OR 要么

if the value in the cell is Yes do an alert and if the value in the cell is No , do another alert 如果单元格中的值为“是”,则执行警报,如果单元格中的值为“ 否” ,则执行另一个警报

Many thanks 非常感谢

Grab the color from the element, then check it as you wish. 从元素中获取颜色,然后根据需要进行检查。 Since jQuery seems to return background-color as an rgb color, you would either have to convert it to hex, or check against the equivalent rgb. 由于jQuery似乎将background-color作为rgb颜色返回,因此您必须将其转换为十六进制,或者检查等效的rgb。

Check out this question if you want a function to convert the color value. 如果您想要一个函数来转换颜色值,请查看此问题

var color = $('td.ms-vb2').css('background-color');
if (color == 'rgb(129,247,159)')
    alert('#81F79F');
else if (color == 'rgb(254,100,46)')
    alert('#FE642E');

Alternatively, you could do a similar bit of code to check the text (this is probably the easier solution in this case) 或者,您可以执行类似的代码检查文本(在这种情况下,这可能是更简单的解决方案)

var value = $('td.ms-vb2').text();
alert(value == "Yes" ? "Yes!" : "No...");

your best bet is to probably add a class to the td if it is yes, or a different class if it is no. 你最好的选择是如果它是肯定的话,可以在td中添加一个类,如果不是,则可以添加另一个类。 and then test basis existence of the class. 然后测试该类的基础存在。

for example add the class affirmative or negative 例如,添加affirmativenegative的类

then in your css have a style for affirmative or negative and declare the background-color there. 然后在你的CSS中有一个肯定或否定的风格,并在那里声明背景颜色。 that way, all your js needs to do is change the class 这样,你所有的js需要做的就是改变这个类

You can use each() function to do all what you need: 您可以使用each()函数执行所需的所有操作:

Set cell background-color: 设置单元格背景颜色:

$('td.ms-vb2').each(function(){
    var cell = $(this)
    if (cell.text() == "Yes")
        cell.css('background-color', '#81F79F');
    else if (cell.text() == "No")
        cell.css('background-color', '#FE642E');        
});

Show alerts: 显示提醒:

$('td.ms-vb2').each(function(){
    var color = $(this).css('background-color');
    if (color == '#81F79F')
        alert('#81F79F');
    else alert('another color');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM