【问题标题】:Set style to html tags by conditions with jQuery使用 jQuery 按条件将样式设置为 html 标签
【发布时间】:2016-05-09 14:10:51
【问题描述】:

下面有html,

<em>+5.0</em>
<em>+3.2</em>
<em>-2.4</em>
<em>-4.6</em>

我想根据条件为每个数字设置颜色。 如果数字大于 0,颜色将为红色。 其他人会是蓝色的。输出将是

+5.0 (red color)
+3.2 (red color)
-2.4 (blue color)
-4.6 (blue color)

如何用 jQuery 做到这一点?

我尝试了什么

if ($('em').text() > 0){
    $(this).css('color', 'red');
}

$('em').text() 不是一个元素,我无法正确应用样式。 我该怎么做?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    你需要使用.each(),来维护this上下文

    $('em').each(function(){
        if (+$(this).text() > 0){
            $(this).css('color', 'red');
        }
    })
    

    或者,可以使用.filter()

    $('em').filter(function(){
        return +$(this).text() > 0;
    }).css('color', 'red')
    

    注意:我使用+ 将文本转换为数字。

    【讨论】:

      【解决方案2】:

      使用 $.each 遍历所有 em,并使用 parseFloat() 。试试这个:

      $('em').each(function(){
        if (parseFloat($(this).text()) > 0){
            $(this).css('color', 'red');
        }
      });
      

      【讨论】:

        【解决方案3】:

        您可以遍历每个em 元素,检查内容并依次应用样式:

        $("em").each(function(){
            if ($(this).text() > 0) {
                $(this).css('color', 'red');
            } else {
                $(this).css('color', 'blue');  
            }
        });
        

        JSFiddle

        【讨论】:

          【解决方案4】:

          您必须使用parseIntparseFloat 将文本转换为整数然后与0 进行比较

          $('em').each(function(){
          var _getText = parseInt($(this).text())
          if(_getText >0){
          $(this).css('color','blue');
          }
          else{
          $(this).css('color','red');
          }
          
          })
          

          检查 Here 是否可以使用 jsfiddle

          【讨论】:

            猜你喜欢
            • 2012-12-20
            • 2013-10-22
            • 2020-08-06
            • 1970-01-01
            • 1970-01-01
            • 2018-10-05
            • 2016-06-06
            • 1970-01-01
            • 2016-06-16
            相关资源
            最近更新 更多