why does the hover and click not always work?

南楼画角 提交于 2019-12-11 07:13:21

问题


here is my fiddle

Pretty much working perfectly apart from sometimes mouseenter, mouseleave, click function (.item) doesn't always work - and needs to be clicked for it to start working again? why is this - here is my code -

       $(document).ready(function () {
     $('.timelineTile').click(function (evt) {
      evt.stopPropagation();
    $('.timelineTile').not(this).removeClass('clicked').find('.pull_down_content').height(0);
      $(this).toggleClass('clicked');

    if(!$('.timelineTile').hasClass("clicked")){
     $(this).children('.pull_down_content').height(0);

       }   


        }); });

     $(document).click(function () {
   $('.timelineTile').removeClass('clicked');
   $('.pull_down_content').height(0);
     $('.inner').stop().css({'display': 'none'}, 300); 
    });


       $(document).ready(function () {
     $('.timelineTile').children('.item').on('mouseenter mouseleave click', function(e) {      e.stopPropagation();
     if ($(this).parent('.timelineTile').hasClass("clicked")) {
    if (!$(this).data('clicked')) {
        var Height = e.type==='mouseenter' ? '90px' : e.type==='click' ? '250px' : '0px';
        $(this).siblings('.pull_down_content').stop().animate({'height': Height}, 300); 

         $(this).siblings('.pull_down_content').children('.inner').css({'display': 'block'},  300); 

        if (e.type==='click') $(this).data('clicked', true);
    }else{
        if (e.type==='click') {
            $(this).data('clicked', false);
            $(this).siblings('.pull_down_content').stop().animate({'height': '0px'}, 300);
   $(this).siblings('.pull_down_content').children('.inner').css({'display': 'none'}, 300);          

        }
    }  

     } 
                 });


     });

I'm not sure if its something to do with this?

    if(!$('.timelineTile').hasClass("clicked")){
     $(this).children('.pull_down_content').height(0);

      }  

回答1:


Try replacing

$('.timelineTile').not(this).removeClass('clicked').find('.pull_down_content').‌​height(0); 

with this

$('.timelineTile').not(this).removeClass('clicked').find('.pull_down_content').‌​height(0).end().find('.item').data('clicked',false); 



回答2:


Maybe you try to attach events when elements aren't exists (for example if they will be added dynamically by scripts).

Use more modern case 'on' instead of 'click' etc.

$(wrapper).on('click', 'element', function() { ... });

Smth like:

...
<div class="wrapper">
    <span class="link">Click me</span>
</div>
...
$('.wrapper').on('click', '.link', function() { ... });

This variant adds events for all elements even if they added dynamically.



来源:https://stackoverflow.com/questions/26384341/why-does-the-hover-and-click-not-always-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!