为什么悬停和单击不总是有效

why does the hover and click not always work?

本文关键字:有效 单击 悬停 为什么      更新时间:2023-09-26

这是我的小提琴

除了有时mouseenter、mouseleave、click函数(.item)并不总是有效之外,几乎可以完美地工作——并且需要单击它才能重新开始工作?为什么这个-这是我的代码-

       $(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);          
        }
    }  
     } 
                 });

     });

我不确定这是否与此有关?

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

尝试更换

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

用这个

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

当元素不存在时(例如,如果它们将由脚本动态添加),您可能会尝试附加事件。

使用更现代的案例"on"而不是"click"等。

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

Smth样:

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

此变体为所有元素添加事件,即使它们是动态添加的。