为什么我的大多数 jquery 函数在将消息预置到现有消息列表后停止工作
Why do most of my jquery functions stop working after prepending a message to an existing list of messages?
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"而不是文档中的文档。
详细地说,在您的示例中,您仅将事件绑定到各个元素,并且在添加新项时,它们没有相同的事件绑定......当您将事件绑定到更高级别的元素时,您基本上是在说"将此处理程序应用于此父元素中与此选择器匹配的所有内容"。
相关文章:
- 要求输入在数据列表中
- 从javascript创建一个列表
- 如何使用jQuery选择下拉列表的值
- 将输入字段中的文本提交到我的数据库,同时将其添加到我的列表中
- 将jsp文件下拉列表中的选定项分配给一个java变量(比如String selection)
- Javascript按钮下拉列表
- 遍历列表,并在jQuery为空时显示消息
- Javascript - 如果任何 2 个选定的下拉列表值相同,如何显示消息框
- 如何编写jQuery-AJAX函数来附加从PHP接收的列表项并显示“正在加载”.“消息,直到收到他的响应
- 如果列表项的内容等于零,则添加消息
- 为列表项 ng 创建唯一的错误消息 - 重复角度
- 为什么我的大多数 jquery 函数在将消息预置到现有消息列表后停止工作
- 正在从json消息更新下拉列表,代码不起作用
- 使用多行列表框使用JS创建消息
- 试图打印消息在我的无序列表框jQuery
- 聊天服务器使用套接字.消息没有添加到列表中
- 我怎样才能得到我的选择呢?列表只在没有选择值时显示消息
- 服务器上列表上的Javascript确认消息
- 下拉列表上的Knockout Validation总是显示错误消息
- 显示'没有项目'使用jQuery插件过滤列表项时的消息