语义-ui模态复制

Semantic-ui modal duplicating

我在路线上有一个 Semantic-ui 模式,最初按预期工作(第一次加载应用程序)。我可以毫无问题地打开和关闭多次。如果我离开路线并再次返回,然后再次单击模态按钮(触发下面的事件),模态 html 将被复制。每次我这样做(导航离开和返回)时,都会添加另一个模式。

我的模式分为两个模板,正如我所读,这是应该的方式。

html:

<template name="contentList">
  {{> addContent}}
  <button class="ui blue button" href="#" id="modal">
    Add Content
  </button>
</template>

<template name="addContent">
  <div id="modal" class="ui small addContent modal">
    {{>addContentForm}}
  </div>
</template>

<template name="addContentForm">
  <!-- Form HTML goes here -->
</template>

js:

Template.contentList.events({
  'click #modal': function(e, t) {
    event.preventDefault();
    $('.ui.modal')
    .modal({
      onApprove : function() {
        $('.ui.modal').modal('hide');
      }
    })
    .modal('show');
  }
});

我需要做什么才能阻止这种行为?

具有多个具有相同 ID 的 dom 元素可能会导致意外行为。 您有一个 ID 为 "modal" 的 div 和一个 ID 为 "modal" 的按钮。更改按钮的id。

嗯,我不觉得自己像个傻瓜...

模态 div 重复的原因是 {{>addContent}} 模态被放置在 div 中。将该代码移出 div 解决了这个问题。我的问题把代码简化太多了!

更新

在使用下面的解决方法进行更多测试后,我遇到了按钮无法响应的问题。在进一步挖掘之后,我偶然发现了 Semantic-ui 的错误报告:https://github.com/Semantic-Org/Semantic-UI/issues/3200.

尽管该问题自 2016 年以来一直存在,但似乎仍未解决。这里提供了几种解决方案。对我来说效果很好的方法是在动态模板的 onCreated 函数中调用 $('body .modals').remove();。您还可以删除给您带来麻烦的特定模式:$('body .modals .addItem')。这样,在添加新模态之前,将首先删除所有旧模态及其事件绑定。我仍然不完全确定这是否正是正在发生的事情,但我的测试似乎支持它。

原版post

我遇到了非常相似的问题。标记的答案不能为我解决。我有一个 div 和模态 class。在其中我通过模板加载内容。它在打开、关闭、导航离开和返回、再次打开后显示两个模式。

我注意到模态框在导航过程中的某处被添加到调光器 div 两次。所以我写了一个小函数来防止多次添加模态。请注意,这是一种解决方法,可能会出现更深层次的问题并产生更大的后果。

Template.editor.helpers({
  modalNotAdded: function(modalClass) {
    //search in .ui.modals div, an element of the dimmer, for modalClass (.addItemModal in this example). If not found, return true.
    return $(".ui.modals").find(modalClass).length == 0;
  }
});
<template name="editor">

  <!-- only add modal if modalNotAdded helper function with argument ".addItem" returns true !-->
  {{#if modalNotAdded ".addItem"}}
  <div class="ui longer modal addItem">
    {{> addItemModal}}
  </div>
  {{/if}}

</template>

<template name="addItemModal">
  <!-- your modal content !-->
</template>