jquery函数根据特殊字符更改文本颜色

jquery function to change text color depending on a special character

本文关键字:文本 颜色 特殊字符 函数 jquery      更新时间:2023-09-26

如果HTML列表中有负数,我想更改文本颜色

这是我对HTML中jquery函数的调用。

<ul id="negativeValidation">
    <li>123.5</li>
    <li>-43.5</li>
</ul>

这是我的jquery函数:

$(document).ready(function() {
    $('#negativeValidation', function() {
        if($("li:contains('-')")== true)
        {
            $("li").css("color", "red");
            console.log("True");
        }else{
            $("li").css("color", "green");
            console.log("False");
        }
    });
});

它不起作用,当我去控制台时,我总是收到"错误"的消息,所以我想知道出了什么问题,或者我是否错过了什么。

$("li:contains('-')")返回一个jQuery对象,该对象始终是truthy,即使该选择器不存在。要测试元素是否匹配,您需要使用lengthis(),但也需要检查每个实例

试试这样的东西:

$('#negativeValidation li').each(function(){
    var color = $(this).is(':contains(-)') ? 'red' :'green';
    $(this).css('color',color);
});

一个更有效的方法是使用CSS并为负添加一个类

#negativeValidation li {color: green}
#negativeValidation li.negative {color: red}

JS-

$('#negativeValidation li').filter(function(){
    return +$(this).text() < 0; 
}).addClass('negative');

首先,在这两种情况下都有console.log('False')

这样写JS Fiddle

$(document).ready(function() {
  $('#negativeValidation li').each(function() {
    var txt = $(this).text();
    if (txt.indexOf('-') > -1) {
      $(this).css("color", "red");
      console.log("True");
    } else {
      $(this).css("color", "green");
      console.log("False");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<ul id="negativeValidation">
  <li>123.5</li>
  <li>-43.5</li>
</ul>

您应该需要"for":

$(document).ready(function() {
$('#negativeValidation', function() {
   var lis = $('#negativeValidation li');
        for (i = 0; i <= lis.length; i++) {
            if (lis.eq(i).is(':contains(-)')) {
                lis.eq(i).css("color", "red");
                console.log("True");
            } else {
                lis.eq(i).css("color", "green");
                console.log("False");
            }
        }

});

});

如果我的HTML列表

但问题标题指的是特殊字符。希望你只是指负数。

因此,以一种纯粹的javascript方式

 // Select all li elements.It will return a collection of matched elements
var getLiItems = document.querySelectorAll("#negativeValidation li");
  // Loop through it , get each's text content ,
      // convert it to float and check if less than 0
 for(var i=0;i<getLiItems.length;i++){
 var getTextContent = parseFloat(getLiItems[i].textContent);
//if less than zero add a class to it
 getTextContent < 0 ? (getLiItems[i].classList.add("negativeColor")): 0;
}

工作示例