如何在父div的鼠标hover上显示子div

我有一些父div(.parent_div),每个包含一个子div(.hotqcontent),我使用循环从我的数据库输出数据。

以下是我目前的加价:

content of first div goes here...

content of second div goes here...

content of third div goes here...

content of fourth div goes here...

我想要实现的是当用户hover/抓住父div时,应该显示其中包含的子div的内容。

为了实现这一点,我编写了以下jQuery脚本,但它似乎没有工作。 它甚至没有显示警报!

  $(document).ready(function() { $(function() { $('.parent_div').hover(function() { alert("hello"); $('.hotqcontent').toggle(); }); }); });  

如何修改或替换现有代码以实现所需的输出?

如果你想要纯CSS而不是像你这样做….

在下面的CSS中,在初始化/页面加载时,我使用display: none;隐藏子元素display: none; 然后在父元素hover时,假设有一个class parent_div ,我使用display: block; 取消隐藏元素。

 .hotqcontent { display: none; /* I assume you'll need display: none; on initialization */ } .parent_div:hover .hotqcontent { /* This selector will apply styles to hotqcontent when parent_div will be hovered */ display: block; /* Other styles goes here */ } 

演示

试试这个

 $(document).ready(function() { $('.parent_div').hover(function() { alert("hello"); $(this).find('.hotqcontent').toggle(); }); }); 

要么

 $(function() { $('.parent_div').hover(function() { alert("hello"); $(this).find('.hotqcontent').toggle(); }); }); 

你可以用css,

 .parent_div:hover .hotqcontent {display:block;} 

这可以用纯css完成(我添加了几个位,只是为了让它更适合JSFIDDLE):

  .parent_div{height: 50px;background-color:#ff0000;margin-top: 10px;} .parent_div .hotqcontent {display: none;} .parent_div:hover .hotqcontent {display:block;} 

如果用户禁用了Javascript,这将确保您的网站仍以相同的方式运行。

演示: http : //jsfiddle.net/jezzipin/LDchj/

使用.hotqcontent您将选择此类的每个元素。 但是您只想选择父级下面的.hotqcontent元素。

 $('.hotqcontent', this).toggle(); 
 $(document).ready(function(){ $('.parent_div').on('mouseover',function(){ $(this).children('.hotqcontent').show(); }).on('mouseout',function(){ $(this).children('.hotqcontent').hide(); });; }); 

的jsfiddle

你不需要document.ready函数..

试试这个

  $(function() { //<--this is shorthand for document.ready $('.parent_div').hover(function() { alert("hello"); $(this).find('.hotqcontent').toggle(); //or $(this).children().toggle(); }); }); 

是的你的代码将切换所有div与类hotqcontent ..(我认为你不需要这个)反正如果你想切换特定div然后使用this引用切换该特定div

更新

您可以在委托事件中使用动态生成的元素

 $(function() { //<--this is shorthand for document.ready $('.content').on('mouseenter','.parent_div',function() { alert("hello"); $(this).find('.hotqcontent').toggle(); //or $(this).children().toggle(); }); }); 

你可以试试这个:

 jQuery(document).ready(function(){ jQuery("div.hotqcontent").css('display','none'); jQuery("div.parent_div").each(function(){ jQuery(this).hover(function(){ jQuery(this).children("div.hotqcontent").show(200); }, function(){ jQuery(this).children("div.hotqcontent").hide(200); } ); }); 

});