【问题标题】:Event firing multiple times inside the same template在同一模板内多次触发事件
【发布时间】:2016-05-10 04:42:15
【问题描述】:

我有这个“评论”模板:

<template name="comment">
  <li class="comment" id="{{_id}}" >

    <div class="comment-wrapper level-{{level}}-comment">
      <span id="reply-btn" class="reply-btn reply-btn-{{_id}}"><a href="#">reply</a></span>
      <div class="content">
        <p>{{body}}</p>
      </div>
    </div>

    <div class="reply-to-comment reply-to-comment-{{_id}}" style="display:none;">
      <form name="reply" class="reply-form">
          <label for="reply_body">Reply to this comment</label>
          <textarea name="reply_body"></textarea>
          <button type="submit" class="btn">Post reply</button>
      </form>
    </div>

    {{#if showChildComments}}
      <ul class="comment-children comment-list">
        {{#each childComments}}
          {{> comment this}}
        {{/each}}
      </ul>
    {{/if}}

  </li>
</template>

与此comment.js 文件相关联(此处仅显示事件部分):

Template.comment.events({
  "click #reply-btn": function(e, template){
    console.log("Got in.")
    $(".reply-to-comment-"+template.data._id).toggle();
  }
});

现在,每次我点击回复时,它都会打开该特定评论的回复表单,如上面的模板所示。

这有效,但仅在“root”cmets 上有效,这意味着:如果我在回复“root”评论的回复上单击回复,console.log("Got in.") 将触发 3 次。如果是5级深度回复会触发5次,以此类推

我怀疑这是因为我在模板“comment”中渲染了模板“comment”。因此,流星正在监听许多“事件”......

但我不知道我怎么能做到这一点。那么,任何人都知道解决此问题的方法,或者更好的方法来实现我正在寻找的东西?

【问题讨论】:

    标签: javascript jquery node.js meteor meteor-blaze


    【解决方案1】:

    可能有些不同,但你所有的 cmets 都有span#reply-btn。

    id 属性为 HTML 元素指定一个唯一的 id(id 属性值在 HTML 文档中必须是唯一的)。

    id 属性可用于指向样式表中的样式。

    JavaScript 也可以使用 id 属性(通过 HTML DOM)来更改具有特定 id 的 HTML 元素。

    具有相同 id 的元素的行为没有明确定义,可能会导致这样的问题。

    【讨论】:

    • 会有意义,但我将事件更改为 "click #reply-btn" 并且发生了同样的事情。
    • 但还是一样。从 span#reply-button 中删除 id 并将 click #reply-btn 更改为 click .reply-btn(它已经拥有该类)。
    • 哦,是的,我的意思是输入"click .reply-btn"。对困惑感到抱歉。下一个答案解决了我的问题。不过感谢您的帮助!
    【解决方案2】:

    您的推理是正确的 - 嵌套模板在导致问题的那些元素上多次注册事件。我认为您可以使用event.stopPropagation() 来阻止事件冒泡。

    【讨论】:

      猜你喜欢
      • 2023-02-02
      • 1970-01-01
      • 2015-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-01
      相关资源
      最近更新 更多