jQuery toggleClass()第一次后不切换类

时间:2019-02-22 17:46:07

标签: javascript jquery

请忽略星号下方的内容。我添加了一个小提琴,因为我提供的摘要不是很有用,然后我首先发布了此摘要。

提琴:https://jsfiddle.net/erobertwald/gc0fod1b/57/

当我单击“菜单1”时,出现模态,并且内容也出现。当我单击面板周围任何位置的模态时,模态消失,并且我假设嵌套的内容也消失了,因为当我再次单击“菜单1”时,模态会出现,但嵌套的内容不会出现。 (不知道为什么,但是在小提琴中,“ X”(关闭)按钮此刻暂时不起作用。)-编辑:如果我具有正确的ID,会有所帮助!)

试图找出导致问题的原因。

*************************原始帖子******************** **********

我已使用以下命令将这些事件添加到元素中:

$(document).on('click', '#site-header > div:nth-child(1)', toggleGalleriesModal);
$(document).on('click', '#modal-close-button', toggleModal);
$(document).on('click', '#modal-backdrop', toggleModal);

哪个每次都会触发此功能:

function toggleGalleriesModal(){
    var content = $('<div id="galleries-modal-content">');
    toggleModal('Galleries', content);
}

在toggleModal()函数中,我切换了模态本身的可见性,然后将内容嵌套在其中:

function toggleModal(label, content){
    window.event.stopPropagation();
    if(content != null) currentModalContent = content;
    currentModalContent.toggleClass('active');
    $('#modal').toggleClass('visible');
}

当我单击#site-header > div:nth-child(1)元素时,将出现模式,并且内容也会出现。当我单击#modal-close-button#modal-backdrop时,模态消失,并且我假设嵌套的内容也消失了,因为当我再次单击#site-header > div:nth-child(1)时,模态出现了,但嵌套的内容却没有。

真的在这里难住了。我一直在追逐自己的尾巴,并在网上寻找,但没有找到解决办法。

1 个答案:

答案 0 :(得分:0)

我找到了。这是其中一种情况,直视我的脸...

在JS中,我有这个:

   var content = $('<div id="galleries-modal-content">');
   if ($('#galleries-modal-content').length == 0) {
       // code to create the galleries-modal-content
   }

哪个元素都是每次创建的,令人震惊的是:每次都擦除了它的内容。

所以我将其更改为:

var content;
if($('#galleries-modal-content').length == 0){
    content = $('<div id="galleries-modal-content">');
    // code to create the galleries-modal-content
}

并添加了另一个:

}
    // code to create the galleries-modal-content
}else{
    content = $('#galleries-modal-content');
}

做到了。