【问题标题】:How do I track changes to my Javascript?如何跟踪对我的 Javascript 的更改?
【发布时间】:2013-01-08 03:32:43
【问题描述】:

我有文本,当您单击它时,背景颜色变为绿色,如果再次单击它,它会变为红色,然后再单击一次它会变回白色。我已成功链接我的 javascript 以将颜色更改为绿色,但我不知道如何跟踪对 javascript 的更改以识别它是绿色,然后将其更改为红色。

我所拥有的是这样的:

<script type="text/javascript">
function change_color($id){

    var link = document.getElementById('link-'+$id);

    var color = link.style.backgroundColor;
    if (color == "green"){
    link.style.backgroundColor="red";
    }if (color == "red"){
    link.style.backgroundColor="white";
    }if (color == "white"){
    link.style.backgroundColor="green";
    }else{
    link.style.backgroundColor="green";
    }

}

</script>

当我运行程序时,它只使用我相信的 else 语句。如何跟踪当前的 backgroundColor 以激活上述 if 语句?

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    如果颜色是绿色,则将其设置为红色。然后下一个条件检查红色(现在为真)并再次更新颜色。

    考虑使用switch 语句而不是if/else 语句。

    【讨论】:

    • 如果你使用switch,请确保在每个案例的末尾都有break,除非你真的想要失败!
    • 天才!工作,也使我的代码的另一部分更有效率,谢谢!!
    • 还有 icktoofay,你真的为我节省了很多时间!
    【解决方案2】:

    如果您想检查多个条件但只运行其中一个,则需要对第一个之后的所有条件使用else if:

    if (color == "green"){
        link.style.backgroundColor="red";
    }else if (color == "red"){
        link.style.backgroundColor="white";
    }else if (color == "white"){
        link.style.backgroundColor="green";
    }else{
        link.style.backgroundColor="green";
    }
    

    【讨论】:

      【解决方案3】:

      在您的if 之间使用if..else if..else 或改用switch-case:

      var color = link.style.backgroundColor;
      var newColor = "green";
      switch (color) {
          case "green":
          {
              newColor="red";
              break;
          }
      
          case "red":
          {
              newColor="white";
              break;
          }
      
          case "white":
          {
              newColor = "green";
              break;
          }
      
          default:
          {
              break;
          }
      }
      
      link.style.backgroundColor = newColor;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-06
        • 1970-01-01
        • 1970-01-01
        • 2010-09-09
        • 2012-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多