远程调用后 jQuery/javascript 停止工作
我有一个页面,其中包含对一篇文章的一组评论和一个 jquery 代码,可以让我在单击它时编辑评论:
comments.js.coffee
$ ->
$(".comment").click ->
html = '''
<form accept-charset="UTF-8" action="/comment?id=''' + $(this).data('value') + '''" data-remote="true" id="updt_comment_form" method="post">
<textarea name="content"> ''' + $(this).children('p').text()+ ''' </textarea>
<input name="commit" type="submit" value="Save">
</form>
'''
$(this).hide()
$(html).insertAfter($(this))
当我提交此表单(远程)时,将呈现以下内容: comments/update.js.erb
$('#comments').replaceWith('<%= escape_javascript(render("comments", :layout => false)) %>');
$('#fresh_comment').show();
$('#fresh_comment').effect("highlight", {}, 3000);
在我提交此表单后,comments.js.coffee 中的 jquery 代码停止工作。下次我单击评论时,我将无法编辑它,除非重新加载页面(这违背了使用 ajax 的目的)。
这是正常的吗?我做错了什么吗?
我能想到的唯一解决方案是重置 update.js.erb 中的 jquery 触发器以使其再次工作......但这似乎不对。
我不明白为什么我的 jquery 代码在执行任何远程调用后停止工作。
提前致谢!
I have a page with a set of comments on an article and a jquery code that lets me edit a comment when i click on it:
comments.js.coffee
$ ->
$(".comment").click ->
html = '''
<form accept-charset="UTF-8" action="/comment?id=''' + $(this).data('value') + '''" data-remote="true" id="updt_comment_form" method="post">
<textarea name="content"> ''' + $(this).children('p').text()+ ''' </textarea>
<input name="commit" type="submit" value="Save">
</form>
'''
$(this).hide()
$(html).insertAfter($(this))
When i submit this form (remotely), the following is rendered:
comments/update.js.erb
$('#comments').replaceWith('<%= escape_javascript(render("comments", :layout => false)) %>');
$('#fresh_comment').show();
$('#fresh_comment').effect("highlight", {}, 3000);
After i submit this form, the jquery code in comments.js.coffee stops working. The next time i click in a comment, i won't be able to edit it, unless i reload the page (which defeats the purpose of using ajax).
Is this normal? Am i doing something wrong?
The only solution i can think of is resetting the jquery trigger in update.js.erb to make it work again... but that doesn't seem right.
I don't see why ANY of my jquery code stops working after executing ANY remote call.
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将点击处理程序委托给容器元素,例如:
当您通过
.replaceWith
替换.comment
时,原始点击处理程序将不再存在。事件委托意味着附加的处理程序将始终工作,因为处理程序绑定到容器元素,而不会被替换。参考:
注意:您也可以使用
.live
为此,但.delegate
有几个比它有优势。You need to delegate the click handler to a container element, e.g.:
When you replace your
.comment
s via.replaceWith
the original click handlers are no longer present. Event delegation means that attached handlers will always work since the handler is bound to a container element, which is not replaced.Reference:
Note: You can also use
.live
for this, but.delegate
has several advantages over it.