jquery - 定位当前div的子元素

标签 jquery html css

我有一个 5 星评级控件,设置如下:

     $('.Star-Rating-Block').each(function() {
        $('.star-rating').hover(
          // Handles the mouseover
          function() {
              $(this).prevAll().andSelf().addClass('star-hover');
          },
          // Handles the mouseout
          function() {
              $(this).prevAll().andSelf().removeClass('star-hover');
          }
        ).click(function() {
           $('.star-rating').removeClass('star-select'); // Removes the selected class from all of them
           $(this).prevAll().andSelf().addClass('star-select').removeClass('star-hover'); // Adds the selected class to just the one you clicked

           var rating = $(this).data('Star-Rating-Block');
        });
      });

不幸的是,有 3 个单独的 .Star-Rating-Block div,每个包含五个具有 .star-rating 类的图像。我想弄清楚如何定位当前事件的 .Star-Rating-Block 的特定子项。我想做到这一点,以便用户可以使用 3 个评级控件中的任何一个,而不会影响其他控件。我觉得我快要完成这个功能了,但我不确定该怎么做才能完成它。我错过了什么?

最佳答案

将当前 block 保存为变量并用作上下文:

$('.Star-Rating-Block').each(function() {
        var container = this;
        $('.star-rating', container).hover(
          // Handles the mouseover
          function() {
              $(this).prevAll().andSelf().addClass('star-hover');
          },
          // Handles the mouseout
          function() {
              $(this).prevAll().andSelf().removeClass('star-hover');
          }
        ).click(function() {
           $('.star-rating', container).removeClass('star-select'); // Removes the selected class from all of them
           $(i).prevAll().andSelf().addClass('star-select').removeClass('star-hover'); // Adds the selected class to just the one you clicked

           var rating = $(this).data('Star-Rating-Block');
        });
      });

请注意 $(i),因为您还没有在任何地方定义 i...

但是,不需要each:

$('.Star-Rating-Block .star-rating').hover(
  // Handles the mouseover
  function() {
      $(this).prevAll().andSelf().addClass('star-hover');
  },
  // Handles the mouseout
  function() {
      $(this).prevAll().andSelf().removeClass('star-hover');
  }
).click(function() {
    var container = $(this).closest('.Star-Rating-Block');
    $('.star-rating', container).removeClass('star-select'); // Removes the selected class from all of them
    $(i).prevAll().andSelf().addClass('star-select').removeClass('star-hover'); // Adds the selected class to just the one you clicked

    var rating = $(this).data('Star-Rating-Block');
});

仍然不确定 $(i) 或为从未使用过的本地 rating 变量赋值的意义何在?

关于jquery - 定位当前div的子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32637260/

相关文章:

php - 如何为外部站点调用基于 javascript 的表单

html - 如何防止CSS动画回到原来的位置?

javascript - 是否可以制作一个自动将文本颜色更改为背景对比度的 Javascript 程序?

html - Chrome 和 Opera 在使用显示 :table 时创建小填充

css - 无法在 WordPress 中制作 css 圆 Angular 表

javascript子函数将返回值传递给父函数返回值

JavaScript - 使用下一个和上一个按钮在数组中移动

jQuery : how to select a checked radio?

javascript - socket.io 的初学者教程好吗?

html - 使用 HTML/CSS 将导航栏居中