Jquery函数没有';第一次点击就不会触发

Jquery函数没有';第一次点击就不会触发,jquery,html,Jquery,Html,我有一个jquery函数,可以扩展线程的注释: function ExpandComments() { $('.showcomments').on('click', function(e) { e.preventDefault(); var comment = $(this).closest('#commentsection').find('.threadComments'); $('#threadComments').not(comment).slideDown();

我有一个jquery函数,可以扩展线程的注释:

function ExpandComments() {
$('.showcomments').on('click', function(e) {
    e.preventDefault();
    var comment = $(this).closest('#commentsection').find('.threadComments');
    $('#threadComments').not(comment).slideDown();
    comment.stop().slideToggle();
});
}  
HTML:

        <h6><a class="showcomments" href="javascript: ExpandComments()">  comments</a></h6>

        <script> $('.threadComments').hide();</script>

        <div class="row">
            <div class="threadComments">

                <div class="large-2 columns small-3"><img src="http://placehold.it/50x50&text=[img]"/></div>
                <div class="large-10 columns"><p>Bacon ipsum dolor sit amet nulla ham qui sint exercitation eiusmod commodo, chuck duis velit. Aute in reprehenderit</p></div>

            </div>
        </div>
        <div class="row">
            <div class="threadComments">
                <div class="large-2 columns small-3"><img src="http://placehold.it/50x50&text=[img]"/></div>
                <div class="large-10 columns"> <textarea id="commentText" style="resize: none;"></textarea></div>

            </div>
        </div>

$('.threadComments').hide();
培根也不愿意坐在阿梅特·努拉·哈姆·奎因(amet nulla ham qui)的位置上练习艾乌斯莫德·康莫多(eiusmod commodo),恰克·杜伊斯·维利特(chuck duis velit)。谴责中的奥特

它工作正常,只是第一次单击时不会触发,正如您的评论所示:我想我应该提到页面是通过load()加载的

当您使用
.load()
加载HTML时,您需要使用委托事件方法

使用


您应该使用最近的静态容器来代替
文档
,以获得更好的性能,您当然不需要
ExpandComments
函数

您是否使用文档就绪处理程序来包装代码?不,我想我应该提一下,页面是通过load()
$('#threadComments')
加载的$('.threadComments')。如果您使用jQuery(或Vanilla Javascript)附加事件处理程序,您的标记中不需要它:
href=“Javascript:ExpandComments()”
。类的选择器使用
符号,而不是用于ID的
。它是$('.threadComments')。不是(comment)。slideDown();或者$(“#threadComments”).not(comment).slideDown()?@RGS,Great eye我完全错过了
<h6><a class="showcomments" href="#">comments</a></h6>
$(document).on('click', '.showcomments', function(e) {
    e.preventDefault();
    var comment = $(this).closest('#commentsection').find('.threadComments');
    $('.threadComments').not(comment).slideDown(); //Also in this a typo use .threadComments
    comment.stop().slideToggle();
});