如果背景为红色,则jQuery无法识别错误,看起来很容易但很固执

jquery if background is red doesn't recognize error, looks easy but stubborn

本文关键字:很容易 看起来 错误 识别 背景 红色 jQuery 如果      更新时间:2023-09-26

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

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

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

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

原因很多。

1) CSS 属性backgroundbackground-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!");
      }
  });
});

工作 Jsfiddle 链接


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

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

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

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

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

因为:

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