【问题标题】:jquery if background is red doesn't recognize error, looks easy but stubbornjquery if background is red 不识别错误,看起来很简单但很顽固
【发布时间】:2013-09-25 19:50:55
【问题描述】:

http://jsfiddle.net/TcSQ8/31/

为什么这个小提琴不起作用?有趣..

$(document).ready(function(){
  $(".box").click(function(){
      if ($(".box").css("background-color") == "red")
      {
          $(".box").html("Success!");
      }
  });
});

【问题讨论】:

  • console.log() 是你的朋友。尝试做console.log($('.box').css('background-color')) 看看它会返回什么。
  • 很高兴。 a 上面的代码显示缺乏努力。查看 jQuery api 可以轻松解决 backgroundstring 问题。
  • 不赞成票的原因是您上面的示例代码中的警报会告诉您 if 检查失败的确切原因。

标签: javascript jquery css


【解决方案1】:

为什么这个小提琴不起作用?

很多原因。

1) CSS 属性background 不是background-color

2) background-color 不是 red 而是 rgb(255, 0, 0)

工作代码:

$(document).ready(function(){
  $(".box").click(function(){

      if ($(".box").css("background-color") == "rgb(255, 0, 0)")
      {
          $(".box").html("Success!");
      }
  });
});

Working Jsfiddle link


旁注:使用console.log() 进行调试比alert() 方便得多

旁注(2):您可以调试 if 语句。在您的情况下,这样的测试可以解决问题。

console.log($(".box").css("background") == "red")

【讨论】:

  • @codinfreak 如果他们想学习而不是复制意大利面,他们将受益于console.log
【解决方案2】:

如果您只是想比较颜色,请获取background-color。之后,在你的条件下使用 rgb 代码,它就可以工作了。

$(document).ready(function(){
  $(".box").click(function(){
      if ($(".box").css("background-color") == "rgb(255, 0, 0)")
      {
          $(".box").append("Success!");
      }
  });
});

【讨论】:

    【解决方案3】:

    因为:

    1. 您将背景(而不是背景颜色)与字符串(红色)进行比较。
    2. css('background') 和 css('backgroundColor') 都会返回元素当前背景颜色的计算 rgb 值。您正在将其与字符串进行比较。

    【讨论】:

      【解决方案4】:
      $(document).ready(function(){
        $(".box").click(function(){
            alert($(".box").css("background-color"));
            if ($(".box").css("background-color") == "rgb(255, 0, 0)")
            {
                $(".box").html("Success!");
            }
        });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-09
        • 2014-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多