Jquery颜色不会切换

时间:2017-04-21 16:03:38

标签: javascript jquery

我需要构建一段非常简单的代码,当您点击<td>时它会变黑,但当您再次点击它时它会变成白色。

$(document).ready(function(){
    $("td").click(function(){
        if($(this).css('background-color') != 'black'){
            $(this).css('background-color', 'black');
        }
        else if($(this).css('background-color') === 'black'){
            $(this).css('background-color', 'white');
        }
    });
});

使用此代码,它将变黑,但不会再变白。

2 个答案:

答案 0 :(得分:3)

它不会再变白,因为"black"只是一个捷径。浏览器将其转换为rgb(0, 0, 0),其绝对严格相等(== vs. ===)为“黑色”

看到这个小提琴:

https://jsfiddle.net/uxnrfh3c/

$(document).ready(function() {
    $("span").click(function() {
        alert($(this).css('background-color')); // alerts rgb(0, 0, 0)
        if($(this).css('background-color') != 'black') {
            $(this).css('background-color', 'black');
        }
        else if($(this).css('background-color') === 'black') {
            $(this).css('background-color', 'white');
        }
    });
});

答案 1 :(得分:1)

为什么不制作一个与你的元素状态相对应的旗帜:

$(document).ready(function(){
  let state = true;
  $("td").click(function(){
    if(state) {
      $(this).css('background-color', 'black');
      state = false;
    } else {
      $(this).css('background-color', 'white');
      state = true;
    }
  });
});