为什么我的大多数 jquery 函数在将消息预置到现有消息列表后停止工作

Why do most of my jquery functions stop working after prepending a message to an existing list of messages?

本文关键字:消息 列表 停止工作 jquery 大多数 函数 为什么 我的      更新时间:2023-09-26

HTML:

<div class='cf' id='content'>
    <div id='leftColumn'>
    </div>
    <div class='microposts'>
      <div class="micropostContent">
      </div
    </div>
    <div id='rightColumn'>
  </div>
</div>

前置:

$('.micropostContent').prepend('<%= j render("users/partials/micropost") %>');

一些功能:

$(".micropost_content").focus(function() {
    this.rows = 7;
    var micropostBox = $(this),
        xButton = $(this).parent().find(".xButton");

          micropostBox.hide().addClass("micropost_content_expanded").show().autoResize();  
          xButton.css("display", "block");
                xButton.click(function() {
                    micropostBox.removeClass("micropost_content_expanded").addClass("micropost_content");
                    micropostBox.val("");
                    xButton.hide();

                });
});

$(".comment_box").focus(function() {
    this.rows = 7;
    var $commentBox = $(this),
        $form = $(this).parent(),
        $cancelButton = $form.children(".commentButtons").children(".cancelButton");
            $(this).removeClass("comment_box").addClass("comment_box_focused").autoResize();  
            $form.children(".commentButtons").addClass("displayButtons");
            $form.children(".commentButtons").children(".cancelButton");
                $cancelButton.click(function() {
                    $commentBox.removeClass("comment_box_focused").addClass("comment_box");
                    $form.children(".commentButtons").removeClass("displayButtons");
                    $commentBox.val("");

                });
});
$('.micropostOptions').on('click',function(){
    var postMenu = $(this).find('.postMenu');
    if(postMenu.is(':hidden') ){
        $('.postMenu').hide();
        $('.micropostOptions').removeClass("postMenuHoverState");
        postMenu.show();
        $(this).hide().addClass('postMenuHoverState').show(60);
    }else{
        postMenu.hide();
        $(this).removeClass("postMenuHoverState");
    }

});

停止工作的函数是焦点和单击功能。它们只有在刷新后才能再次工作,直到我发布另一个 ajax 消息/微帖子。

.comment_box 函数不适用于已添加前缀的消息,但它适用于所有以前的消息。.micropostOptions 功能并非全部有效。然后刷新后一切正常。

我错过了什么吗?

亲切问候

因为事件仅在声明它们时绑定到现有项目.. 声明使用 on 并附加到父元素

$(document).on("focus", ".comment_box", function() {
//this will work with new elements 
});

父容器越接近您附加功能的元素越好,例如父容器".cf"或".microposts"而不是文档中的文档。

详细地说,在您的示例中,您仅将事件绑定到各个元素,并且在添加新项时,它们没有相同的事件绑定......当您将事件绑定到更高级别的元素时,您基本上是在说"将此处理程序应用于此父元素中与此选择器匹配的所有内容"。