单击下一个弹出窗口时,第一个弹出窗口不会关闭

时间:2013-12-11 19:46:42

标签: javascript jquery performance html popup

我希望弹出窗口一次只出现一个,无论弹出多少弹出窗口。因此,如果一个弹出窗口当前打开,它将关闭,新的弹出窗口将保持打开状态。我目前对它们进行了编码,因此初始链接将打开并关闭弹出窗口,用户应该能够单击文档中的任意位置以在打开后关闭弹出窗口。

我有一个jsfiddle here

我对此代码的问题:

1.如果选择了另一个,则点击的第一个弹出窗口不会消失 2.如果你点击初始链接以外的任何地方关闭它,你必须双击链接才能重新出现弹出窗口。 3.所有弹出窗口应该最初关闭

HTML:

<div id="link"><a href="#" class="showPopup" rel="one"> One</a></div>
<div class="popup popup_hide" id="one">Content</div>

<div id="link"> <a href="#" class="showPopup" rel="two"> Two</a></div>
<div class="popup popup_hide" id="two">Content <a href="#">link</a></div>

<div id="link"> <a href="#" class="showPopup" rel="three"> Three</a></div>
<div class="popup popup_hide" id="three">Content <a href="#"></a></div>

使用Javascript:

jQuery(document).ready(function() {

var popupStatus = 0;

if (popupStatus == 0) { // if value is 0, show popup
        $('.showPopup').click(function () {
            $('#' + $(this).attr('rel') + '_img').removeClass('border_grey');
            if ($(this).hasClass("selected")) {
                $('#' + $(this).attr('rel')).hide();
                $(this).removeClass("selected");
            } else {
                $(this).addClass("selected");
                $('#' + $(this).attr('rel') + '_img').addClass('border_grey');
                $('#' + $(this).attr('rel')).show();
                popupStatus = 1; 
            }

         return false;
        });

    }
 else if (popupStatus == 1){
         $('.popup').hide();
         popupStatus = 0;
    }

    $('.hide_popup').click(function () {
        $('img').removeClass('border_grey');
        $('.popup').hide();
        return false;
    });

    $(document).click(function (e) {
        if (e.target.class !== 'popup_hide') {
            $('.popup_hide').hide();
        }
    });

}); // jQuery End

2 个答案:

答案 0 :(得分:0)

首先要提到的是,你应该重写你的html,因为它包含同名的Id,不应该是,因为元素Id应该是唯一的。

我不确定这是否是你要找的,但我稍微更新了你的代码,所以这可能是你的一个起点

HTML

<div id="link1"> 
    <a href="#" class="showPopup" rel="popup_brain"> hello</a>
</div>
<div class="popup popup_hide" id="popup_brain">Content</div>
<div id="link2"> <a href="#" class="showPopup" rel="heart"> Goodbye</a> 
</div>
<div class="popup popup_hide" id="heart">Content <a href="#">hi</a></div>

JS

jQuery(document).ready(function(){

  $('.popup_hide').hide()

  $('#link1').click(function(){
          $('#popup_brain').show()
          $('#heart').hide()
  })

  $('#link2').click(function(){
          $('#heart').show()
          $('#popup_brain').hide()
  })

})

最佳

答案 1 :(得分:0)

这可能会满足您的需求:

jsFiddle Demo

var rr, popupStatus = 0;

$('.popup').hide();

$('.showPopup').click(function (e) {
    rr = $(this).attr('rel');
    $('.popup').hide();
    $('#' + rr).show();
    e.stopImmediatePropagation();
});

$(document).click(function (e) {
    if (e.target.class !== 'popup_hide' && e.target.class !== 'showPopup') {
        $('.popup_hide').hide();
    }
});