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

时间:2016-01-04 02:39:05

标签: javascript jquery

如果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");
        }

    });

});

它不起作用,当我去控制台时,我总是得到“错误”的消息,所以我想知道什么是错的,或者我是否遗漏了什么。

4 个答案:

答案 0 :(得分:3)

$("li:contains('-')")返回一个jQuery对象,即使该选择器不存在,该对象也总是很简单。要测试元素是否匹配,您需要使用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');

答案 1 :(得分:1)

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

像这样写JS Fiddle

&#13;
&#13;
$(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");
    }

  });

});
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

你需要&#34;对于&#34;:

$(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");
            }

        }


});

});

答案 3 :(得分:0)

  

如果我的号码中有负数,我想更改文字颜色   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;
}

Working Example