【问题标题】:JQuery LT Selector Working but GT Is NotJQuery LT 选择器工作但 GT 不是
【发布时间】:2012-04-13 22:22:47
【问题描述】:

我正在研究星级选项。我有一个包含隐藏输入和五个图像的跨度。当其中一个图像悬停在上面时,该图像和左侧的每个同级图像都会设置为图像的突出显示版本,而右侧的每个同级图像都会变暗。

HTML

<span>
 <input type="hidden" value="1" class="starCount">
 <img src="star-on.jpg" alt="Rating:1 Star" class="rating"><!--
 --><img src="star-off.jpg" alt="Rating:2 Stars" class="rating"><!--
 --><img src="star-off.jpg" alt="Rating:3 Stars" class="rating"><!--
 --><img src="star-off.jpg" alt="Rating:4 Stars" class="rating"><!--
 --><img src="star-off.jpg" alt="Rating:5 Stars" class="rating">
</span>

jQuery

click: (function(){
  // Set the hidden input value to which rating you clicked
  $(this).siblings(".starCount:eq(0)").val($(this).index());
}),
mouseover: (function(){
  // Highlight the star being hovered + all stars to the left
  $(this).attr("src","star-on.jpg");
  $(this).prevAll(".rating").attr("src","star-on.jpg");
  $(this).nextAll(".rating").attr("src","star-off.jpg");
}),
mouseout:(function(){
  // Reset highlighted stars to the value of the hidden input

  // Get the position of the hovered element
  var stars = parseInt($(this).siblings(".starCount:eq(0)").val());

  if($(this).index() != stars){
    // Highlight this element and everything to it's left
    $(this).siblings(".rating:lt("+(stars-1)+")").attr("src","star-on.jpg");

    // Dim everything to the right
    /* -- Note this line: It works, but is where my question derives from -- */
    $(this).siblings(".rating:eq("+(stars-1)+")").nextAll().attr("src","star-off.jpg");
  }
})

我的问题是我必须如何完成“调光”部分。这适用于 [this element] + 以前的兄弟姐妹:

$(this).siblings(".rating:lt("+(stars-1)+")").attr("src","star-on.jpg");

为什么这对之后的所有内容都不起作用:

$(this).siblings(".rating:gt("+(stars-1)+")").attr("src","star-off.jpg");

我刚刚注意到我没有解释 什么 在使用 GT 选择器时不起作用。这是我如何重现我的问题。 见http://jsfiddle.net/SNmcB/1/

  • 点击第三颗星。
  • 将鼠标悬停在星号 1 上并退出;它会重置为选中的 3 个。
  • 点击第一个星。
  • 将鼠标悬停在星号 4 或 5 上并退出;您悬停在上面的星星仍然突出显示。
  • 如果我使用 nextAll() 方法而不是 GT,则不会发生这种行为。

【问题讨论】:

  • 能否提供用于渲染星星的html sn-p?
  • 添加了 JSFiddle + 更好地解释了我的问题。我没有意识到我让你们猜到了多少。

标签: jquery jquery-selectors siblings


【解决方案1】:

第一颗星的兄弟姐妹是:2 3 4 5

没有 gt() 选择器可以选择这个。

第二颗星的兄弟姐妹是:1 3 4 5 gt参数需要为0。

3 号星

兄弟姐妹:1 2 4 5

需要的索引:1

4 号星

兄弟姐妹:1 2 3 5

需要的索引:2

五号星

兄弟姐妹:1 2 3 4

需要的索引:3

所以以下应该可以工作:

if (stars === 1) {
    $(this).nextAll().attr("src","star-off.jpg");
} else {
    $(this).siblings(".rating:gt("+(stars - 2)+")").attr("src","star-off.jpg");
}

【讨论】:

  • 非常非常接近。尽管您的解决方案与我的错误相同,但您让我找到了问题所在。 There is no gt() selector that can select this: 除了触发 mouseout 的元素外,一切都设置为正常;它跳过了自己,因为它不在它的兄弟集合中,但 nextAll 不关心集合;只是选定的元素。
猜你喜欢
  • 2010-11-11
  • 2011-05-11
  • 2017-04-10
  • 2011-03-16
  • 2021-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-16
相关资源
最近更新 更多