【发布时间】:2017-03-15 23:35:46
【问题描述】:
我正在使用 jQuery .replaceWith 方法使用户能够回复或取消对帖子的评论。回复按钮的工作原理是单击时会创建一个文本框。但是,单击取消按钮会刷新页面,而不是在不重新加载页面的情况下返回原始帖子。如何使取消按钮正常工作?感谢您的帮助!
<form method="post">
<input type="hidden" name="post_id" value="{{ p.key.id() }}">
<input type="hidden" name="user_id" value="{{ user.key.id() }}">
<input type="button" name="reply" id="{{ p.key.id() }}" value="Reply">
</form>
<script>
$("#{{ p.key.id() }}").click(function() {
var reply = $("<textarea name='reply_content' style='resize: none; width: 550px; height: 100px;'></textarea><br><input type='submit' name='reply' value='Reply'><input type='submit' id='cancel_{{ p.key.id() }}' value='Cancel'>")
$("#{{ p.key.id() }}").replaceWith(reply);
});
$("#cancel_{{ p.key.id() }}").click(function() {
var cancel = $("<input type='button' name='reply' id='{{ p.key.id() }}'' value='Reply'>");
$("#{{ p.key.id() }}").replaceWith(cancel);
});
</script>
【问题讨论】:
-
jQuery 选择器中的 {{ p.key.id() }} 是什么?
-
@calcazar 我正在使用 Jinja2 模板,所以我将一个变量从服务器端传递给我的模板。
-
cancel_whateverid 是动态添加的,因此您必须在添加事件时绑定事件,或者使用委托。受骗者有代码示例。 (请注意,“接受”的答案并不总是最好的)
-
@KevinB 非常感谢您的帮助。我会尝试后者,因为当我尝试绑定事件时,取消按钮变得无响应。
标签: javascript jquery html forms replacewith