【问题标题】:jQuery show/hide rendering duplicate contentjQuery 显示/隐藏渲染重复内容
【发布时间】:2013-04-11 22:51:35
【问题描述】:

我对 jquery 还很陌生,所以请耐心等待。我正在对多个 div 进行简单的显示/隐藏。基本上,您将鼠标悬停在具有类的图像上,并显示来自具有相应类的 div 的内容。我遇到的事情是,如果您将鼠标悬停在一个图像上,然后将鼠标悬停在另一个图像上,那么在某些情况下,我会看到上一个悬停的内容,而当前悬停的内容基本上是重复的内容。这实际上只有当您快速悬停在图像上但仍然很烦人时。任何想法为什么会发生这种情况?

jQuery('document').ready(function(){

  jQuery('.company').not(':first').hide();

  jQuery('#company_container img').on('hover', function(){

var contenttoShow = jQuery(this).attr('data-title');

    contenttoShow2 = jQuery(contenttoShow);
    jQuery('.company').hide();
    contenttoShow2.fadeIn(500);
  });

});

<div class="company" id="company_1">
<p>some content goes here</p>
</div>

<div class="company" id="company_2">
<p>some content goes here</p>
</div>

<div class="company" id="company_3">
<p>some content goes here</p>
</div>

<div id="company_container">
 <a title="" href="#"><img data-title="#company_1" src="test.jpg" /></a>
 <a title="" href="#"><img data-title="#company_2" src="test2.jpg" /></a>
 <a title="" href="#"><img data-title="#company_3" src="test3.jpg" /></a>
</div>

【问题讨论】:

    标签: jquery performance


    【解决方案1】:

    让我知道这是否适合你...

    jQuery('.company').not(':first').hide();
    
    jQuery('#company_container img').mouseover(function() {
       jQuery('.company').hide();
       var contenttoShow = jQuery(this).attr('data-title');
       jQuery(contenttoShow).fadeIn(500);      
    
    });
    

    http://jsfiddle.net/ba6SZ/

    【讨论】:

    • 感谢@Loren,但我真的很困惑为什么这会更好。任何想法,非常感谢!
    【解决方案2】:

    改用.hover()

    jQuery('#company_container img').hover(function () {
    

    Demo

    【讨论】:

      【解决方案3】:

      jQuery .on() 是 Attach an event handler function for one or more events to the selected elements.

      http://api.jquery.com/on/

      通常用于将事件附加到动态创建的元素。

      注意多事件绑定。在这个小演示中,每次单击该框时,都会以 2^x 的次数增加它。 (x 是点击次数)。这让我前一阵子摸不着头脑。

      http://jsfiddle.net/chrisloughnane/acNwn/

      【讨论】:

        猜你喜欢
        • 2014-07-08
        • 1970-01-01
        • 1970-01-01
        • 2018-06-16
        • 2017-10-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多