2016-07-29 74 views
0

我有一个打开一个小窗口来显示额外信息的按钮。 目前它只打开,我不得不点击关闭按钮关闭它,我真的不希望这个关闭按钮,但我希​​望能够打开和关闭它与同一个按钮。jquery打开并关闭同一个按钮

$(function() { 
    //----- OPEN 
    $('[data-popup-open]').on('click', function(e) { 
     var targeted_popup_class = jQuery(this).attr('data-popup-open'); 
     $('[data-popup="' + targeted_popup_class + '"]').fadeIn(350); 

     e.preventDefault(); 
    }); 

    //----- CLOSE 
    $('[data-popup-close]').on('click', function(e) { 
     var targeted_popup_class = jQuery(this).attr('data-popup-close'); 
     $('[data-popup="' + targeted_popup_class + '"]').fadeOut(350); 

     e.preventDefault(); 
    }); 
}); 

任何人都可以帮助我吗?

+1

因为点击事件绑定到当时存在的项目,所以应该使用事件委派。 –

+0

也许你应该使用'.toggle'来代替。 –

+0

@ DanielA.White悬停在日历中的for循环中创建,它们可能会也可能不会被创建,具体取决于当天有多少事件,所以我需要它来绑定到项目。 –

回答

1

尝试fadeToggle()jQuery函数。

$('button').on('click', function(e) { 
    var targeted_popup_class = jQuery(this).attr('data-popup-open'); 
    $('[data-popup="' + targeted_popup_class + '"]').fadeToggle(350); 

    e.preventDefault(); 
}); 
+0

美丽,你明白了!我会尽快解决~5min, 谢谢! –

1
$('[data-popup-open-close]').on('click', function(e) { 
     if(!$(this).hasClass("opened")){ 
     //code for open 
     $(this).addClass("opened") 
     }else{ 
     //code for close 
     $(this).removeClass("opened") 
     } 
    }); 
+1

这对我来说似乎是更好的解决方案,因为它将样式中的打开/关闭逻辑解耦(可以在CSS中设置) – Carlo

0

你只需要了解,当你点击,如果该层打开或关闭和后果的反应。

我已经使用$(..).is(':visible')作为示例,但您必须为您的方案找出最佳功能。

喜欢的东西..

$(function() { 

    //----- OPEN and CLOSE 
    $('[data-popup-close]').on('click', function(e) { 
     var targeted_popup_class = jQuery(this).attr('data-popup-close'); 

     // for example 
     var isOpen = $('[data-popup="' + targeted_popup_class + '"]').is(':vivible'); 

     if (isOpen) { 
      $('[data-popup="' + targeted_popup_class + '"]').fadeOut(350); 
     } else { 
      $('[data-popup="' + targeted_popup_class + '"]').fadeIn(350); 
     } 


     e.preventDefault(); 
    }); 
}); 
0

除了fadeToggle()方法,你可以知道,如果一个框是可见或不可见:

$('button').on('click', function(e) { 
    var targeted_popup_class = jQuery(this).attr('data-popup-open'); 
    if($('[data-popup="' + targeted_popup_class + '"]').is(':visible')) { 
     //close it! 
    } else { 
     // open it! 
    } 

    e.preventDefault(); 
}); 
0

我希望它应该是适合你的工作。

$(function() { 
    $('[data-popup-open]').on('click', function(e) { 
     if($(this).hasClass('data-popup-open')) 
     { 
      $('[data-popup="' + targeted_popup_class + '"]').fadeOut(350); 
     } 
     else if($(this).hasClass('data-popup-close')) 
     { 
      $('[data-popup="' + targeted_popup_class + '"]').fadeIn(350); 
     } 
     $(this).toggleClass('data-popup-open') 
     $(this).toggleClass('data-popup-close') 
     e.preventDefault(); 
    }); 
}); 
相关问题