jQuery 颜色变化只是短暂闪烁,不是永久性的

jQuery color change only flashes briefly, is not permanent

我正在尝试让一个列表项在单击时永久更改字体颜色,在本例中是从绿色变为黄色。但是,下面的代码在单击时只会闪烁黄色半秒钟,然后默认为绿色。正如预期的那样,下划线样式会永久应用:

<!DOCTYPE html>
        <html>
        <head>
     <script type = "text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
     <script>
        $(document).ready(function(){
            $('li').hover(function(){
                $(this).css('color', 'white')
             }, function(){
                $(this).css('color', '')
            });

            $("#resources").click(function(){
        $("#resources").css('text-decoration', 'underline');
        document.getElementById("resources").style.color = "yellow";
      });
        });
        </script>
        <style>
         #main{
          margin: 0 auto;
    text-align: center;
    background: black;
    color: green;
    font-family: Courier;
    position: relative;
    top: 300px;
    width: 100%;
   }

         li{
       display: inline;
       padding: 8px;
       padding-right: 1em;
       position: relative;
     }
         li:hover{
       color: white;
   }
      ul{
       text-align: center;
      }

         </style>
     </head>
    <body>
     <div id = "main">
      <ul id = "main_links">
       <li id = "resources">Resources</li>
      </ul>
     </div>

    </body>
    </html>

我相信这是因为你的悬停功能的第二个功能是重置颜色。您甚至根本不需要 li hover 功能吗?该样式应由 CSS 应用。如果你删除它,我的猜测是即使你点击它,颜色也应该保持黄色。

由于以下代码,只有在您将鼠标移开之前它才会保持黄色:

        $('li').hover(function(){
            $(this).css('color', 'white')
            }, function(){
            $(this).css('color', '')
        });

您可以删除该代码并添加以下样式:

li.clicked {
    color: yellow;
    text-decoration: underline;
}

并将 javascript 更改为:

$(document).ready(function () {
    $("#resources").click(function () {
        $(this).addClass('clicked');
    });
});

jsfiddle

尝试用 .mouseenter() , .mouseleave() 代替 .hover() ;在 #resources .click() 事件

中调用 $(this).off()

$(document).ready(function() {
  $('li').mouseenter(function() {
    $(this).css('color', 'white')
  }).mouseleave(function() {
    $(this).css('color', '')
  });

  $("#resources").click(function() {
    $(this).css({
        "text-decoration": "underline"
        , "color": "yellow"
      })
      .off("mouseenter mouseleave")
  });

});
#main {
  margin: 0 auto;
  text-align: center;
  background: black;
  color: green;
  font-family: Courier;
  position: relative;
  top: 300px;
  width: 100%;
}
li {
  display: inline;
  padding: 8px;
  padding-right: 1em;
  position: relative;
}
li:hover {
  color: white;
}
ul {
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>


<body>
  <div id="main">
    <ul id="main_links">
      <li id="resources">Resources</li>
    </ul>
  </div>
</body>