第一次单击时不会触发Jquery函数

时间:2014-08-26 09:02:59

标签: jquery html

我有一个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>

一切正常,只有在第一次点击时才触发

1 个答案:

答案 0 :(得分:1)

根据您的评论:我想我应该提一下该页面是通过load()加载的

在使用.load()加载HTML时,您需要使用Event Delegation委托事件方法{。}}。

使用

<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();
});

代替document你应该使用最接近的静态容器以获得更好的性能,你当然不需要ExpandComments功能

相关问题