-->

why does the hover and click not always work?

2019-08-09 00:41发布

问题:

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.