2010-05-11 86 views
2

我想悬停一个图像,并弹出一个div,没有插件。只是基本的jQuery 的jQuery是这样的:简单的jQuery问题,嵌套选择器和父

<script type="text/javascript"> 
$(document).ready(function() { 
    $(".wrapperfortooltip div img").hover(
     function() { 
      $(this).css('border', 'solid 1px #E90E65'); 
      $("div", this).stop().fadeIn(); 
     }, 
     function() { 
      $(this).css('border', '1px solid #3E3D3D'); 
      $("div",this).stop().fadeOut(); 
     } 
    ); 
}); 
</script> 

的HTML是这样的:

<div class="wrapperfortooltip"> 
    <div style="position:relative;"> 
     <img src="images/question.gif" alt="Tooltip" style="border: 1px solid #3E3D3D;" /> 
     <div class="tooltipVzw" style="position: absolute; display: none; width: 215px; top: 0px; left: -235px; "> 
      Message to display nr one 
     </div> 
    </div> 
    <div style="position:relative;"> 
     <img src="images/question.gif" alt="Tooltip" style="border: 1px solid #3E3D3D;" /> 
     <div class="tooltipVzw" style="position: absolute; display: none; width: 215px; top: 0px; left: -235px; "> 
      Message to display 
     </div> 
    </div> 
</div> 

的CSS(对他们来说可能有兴趣)

.tooltipVzw 
{ 
    border: solid 1px #3e3d3d; 
    color: #cfc6ca; 
    font-size: 11px; 
    padding: 9px 9px 9px 9px; 
    background-image: url(images/tooltipvzwbg.jpg); 
    background-repeat:repeat-x; 
    background-color:#1c1c1c; 
    text-align:left; 
    line-height: 16px; 
} 

现在我要找到办法做修改

$("div", this).stop().fadeIn(); 

到这样的事情:

$(this).parent().("div").stop().fadeIn(); 

所以我的实际问题是;我如何修复上面的行以便它能够正常工作。还是我完全错了?

感谢先进!

+1

查看答案他人下面给出。只要你明白了,你提供的最后一行代码就差不多了。你只是缺少一个像$(this).parent()。find(“div”)。stop()。fadeIn();这样的函数名;'然而,给出的答案会更有效率。 – user113716 2010-05-11 14:20:01

+0

感谢帕特里克的回答。现在我学到了两种方法! – 2010-05-11 14:26:59

回答

5

由于div似乎总是img后,你可以只使用.next()元素:

$(this).next().stop().fadeIn(); 

或过滤器,以在安全方面:

$(this).next('.tooltipVzw').stop().fadeIn(); 
+1

适用于相应的类选择器。如果工具提示的相对位置不确定,'.siblings('。tooltipVzw')'也可以使用。 – user113716 2010-05-11 14:23:55

+0

@帕特里克:好点。 – 2010-05-11 14:26:07

0

你可以使用

$(this).next().stop().fadeIn(); 

此找到下一个兄弟和显示。它强烈依赖于DOM结构。更通用的解决方案可能是使用$(this).nextAll('div')...$(this).parent().find('div')...