【问题标题】:Not removing class or adding class不删除类或添加类
【发布时间】:2022-01-22 22:03:12
【问题描述】:

我正在尝试制作一个星级评分系统,并且我设法做到了,这样您就可以将星星设为黄色。当我再次单击星星时,它们不会变白。换句话说,我需要帮助来切换星星,以便它们改变颜色。我是html的初学者,所以我不知道问题是什么。任何帮助,将不胜感激!这是我的代码:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Star Rating</title>
    <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
    <script>
    $(function() {
      $(".n").click(function() {
        $(this).attr('src', 'star_checked.png');
        $(this).removeClass("n");
        $(this).addClass("y");
      });
      $(".y").click(function() {
        $(this).attr('src', 'star.png');
        $(this).removeClass("y");
        $(this).addClass("n");
      });
    });
    </script>
    <style>
      div#rating {
        background-color: #eeeeee;
        width: 200px;
        height: 500px;
        border-radius: 20px;
      }
    </style>
  </head>
  <body>
    <div class="stars">
      <img class="y" src="star_checked.png" alt="" width="100" height="100">
      <img class="y" src="star_checked.png" alt="" width="100" height="100">
      <img class="n" src="star.png" alt="" width="100" height="100">
      <img class="n" src="star.png" alt="" width="100" height="100">
      <img class="n" src="star.png" alt="" width="100" height="100">
    </div>
  </body>
</html>

这是我的图片:White StarYellow Star

【问题讨论】:

  • 试试$(".stars").on("click",".n",function() {

标签: html jquery


【解决方案1】:

您应该为此使用jquery.on。请参阅下面的工作代码。

$(function() {
  $(".stars").on("click", ".n", function() {
    $(this).attr('src', 'https://i.stack.imgur.com/gwKvQ.png');
    $(this).removeClass("n");
    $(this).addClass("y");
  });
  $(".stars").on("click", ".y", function() {
    $(this).attr('src', 'https://i.stack.imgur.com/Lfswl.png');
    $(this).removeClass("y");
    $(this).addClass("n");
  });
});
div#rating {
  background-color: #eeeeee;
  width: 200px;
  height: 500px;
  border-radius: 20px;
}
<!DOCTYPE html>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>


<div class="stars">
  <img class="y" src="https://i.stack.imgur.com/gwKvQ.png" alt="" width="100" height="100">
  <img class="y" src="https://i.stack.imgur.com/gwKvQ.png" alt="" width="100" height="100">
  <img class="n" src="https://i.stack.imgur.com/Lfswl.png" alt="" width="100" height="100">
  <img class="n" src="https://i.stack.imgur.com/Lfswl.png" alt="" width="100" height="100">
  <img class="n" src="https://i.stack.imgur.com/Lfswl.png" alt="" width="100" height="100">
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-07
    • 2018-08-02
    • 1970-01-01
    • 2011-03-05
    • 2021-11-27
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多