jQuery:麻烦遍历

时间:2009-09-14 22:02:47

标签: jquery

我试图找到一些关于遍历jQuery的体面文档,但是没有找到合适的资源,任何建议都会非常感激。

我正在尝试为菜单创建一个简单的动画。

我有一个简单的菜单:

<ul class='contentNav'>
 <li><a href='#'>One</a>
 <li><a href='#'>Two</a>
 <li><a href='#'>Three</a>
 <li><a href='#'>Four</a>
</ul>

一个简单的jquery函数来改变标签的背景颜色:

$(document).ready(function(){

   $(".contentNav a").hoverIntent(
   function(over) {
     $(this).animate({backgroundColor: "#844"}, "fast");
     $(this).parent().find("li a").animate({backgroundColor: "#090"}, "fast");
   },
   function(out) {
     $(this).animate({backgroundColor: "#000"}, "fast");
     $(this).parent().find("li a").animate({backgroundColor: "#000"}, "fast");
   });
}); 

麻烦在于:

$(this).parent().find("li a").animate({backgroundColor: "#090"}, "fast"); 
$(this).parent().find("li a").animate({backgroundColor: "#000"}, "fast");

我正在尝试选择当前没有悬停的所有链接标记项并设置其背景颜色。我该怎么做呢。

感谢。


更新


我已经采纳了所有建议并提出以下代码:

$(this).parent().parent().find("a").not(this).animate({backgroundcolor: "#555"}, 100)

4 个答案:

答案 0 :(得分:6)

您的行缺少额外的父级:

$(this).parent().parent().find("li a").animate({backgroundColor: "#090"}, "fast"); 
$(this).parent().parent().find("li a").animate({backgroundColor: "#000"}, "fast");

由于您的初始选择器位于“a”标记上,因此您希望一次转到“li”标记,然后再转到包含div,如果您想使用find(“li a”)选择器。

答案 1 :(得分:4)

hoverIntent docs开始,hoverIntent调用采用配置对象,而不是两种方法。试试这个:

$(document).ready(function(){
  $(".contentNav a").hoverIntent({
    over: function() {
      $(this).animate({backgroundColor: "#844"}, "fast");
      $(this).parent().parent().find("li a").not(this).animate({backgroundColor: "#090"}, "fast");
    },
    out: function() {
      $(this).parent().parent().find("li a").animate({backgroundColor: "#090"}, "fast");
    }
  });
});

his answer提供丰富的资产,以确定祖父母的问题。 另一个是Vertigo for the idea使用临时类和not

答案 2 :(得分:4)

如果你想选择所有但悬停的元素你可以做这样的事情:

// first add class to hovered element when hovering over
$(this).addClass("hovered");
// then select all but that one
$(this).parent().parent().find("li a").not(".hovered").animate({backgroundColor: "#090"}, "fast");

// and remember to remove class when hovering out
$(this).removeClass("hovered");

答案 3 :(得分:1)

Vertigo使用临时类的想法应该适用于选择除了悬停元素之外的所有元素(+1)。

但是,另一种方法也应该是使用filter()方法,并比较dom元素实例。这种方法可能比添加和删除类名略快,但如果存在性能差异,则可能非常小。

$(document).ready(function(){
   $(".contentNav a").hoverIntent(
   function(over) {
     var current = this;
     $(this).animate({backgroundColor: "#844"}, "fast");
     $(this).parent().parent()
         .find("li a")
         .filter(function() { return this !== current; })
         .animate({backgroundColor: "#090"}, "fast");
   },
   function(out) {
     var current = this;
     $(this).animate({backgroundColor: "#000"}, "fast");
     $(this).parent().parent()
         .find("li a")
         .filter(function() { return this !== current; })
         .animate({backgroundColor: "#000"}, "fast");
   });
});
相关问题