javascript - 从 $().html() 触发表单提交按钮
问题描述
我有这样一个模板,当用户点击编辑字形图标时,它会提示一个表单进行进一步编辑:
<div class="post-menu pull-left">
<a class="editCommentLink" href="#">
<span id="{{ comment.id }}" class="glyphicon glyphicon-edit" aria-hidden="true">edit </span>
</a>  
<a class="delCommentLink" id="{{ comment.id }}" href="#">
<span id="{{ comment.id }}" class="glyphicon glyphicon-trash" aria-hidden="true">delete</span>
</a>
</div>
我使用 ajax 发送 get 请求并用$commentNew.html(commentEditForm)
;更新内容。
<script>
$(document).ready(function(){$(".editCommentLink").on("click", function(e) {
e.preventDefault()
var comment_id= $(e.target).attr("id")
// Retrieve the top node of comment-right
var $commentRight= $(e.target).closest(".comment-right")
$.ajax({
type: "GET",
url: `/ article/comment/edit /${comment_id}`,
success: function(data){
var ret=JSON.parse(data)
var body=ret['body']
var commentEditForm= `
<form action="#" method="post" > {% csrf_token % }
< div class="form-group" >
< textarea class="form-control" name="comment" id="editComment${comment_id}" >${body} < /textarea >
< button class="btn btn-primary" id="editSubmitBtn" > Save Edits < /button >
<a href="#" > cancel < /a >
< / div >
< /form >
`
var $commentNew= $commentRight.find(".post-text");
$commentNew.html(commentEditForm);
}, // success
});//end of ajax
})//end edit click
</script>
但是,当我触发按钮id="editCommentBtn"
提交表单数据时,没有反馈,
});//end of ajax
})//end edit click
$(document).ready(function (e) {
//still in edit click event
$("#editCommentBtn").on("click", function (e) {
e.preventDefault();
alert('button clicked');
...
});//submit click event
})
我尝试解决这个问题,让我感到困惑的是,如果我更改$(".editCommentBtn")
为它的祖父母$(".post-text")
,浏览器会提醒我(“点击按钮”),
我试图将大部分元素分解var commentEditForm=
为单个元素,例如:
$newForm = $('<form action="#" method="post" > {% csrf_token % } < /form >');
$newFormGroup = $('< div class="form - group" >< / div >');
$newText = $('< textarea class="form-control" name="comment" id="editComment${comment_id}" >${body} < /textarea >');
$newSubmit = $('< button class="btn btn-primary" id="editCommentBtn" > Save Edits < /button >')
$(.post-text).append($newForm);
$newForm.append($newFormGroup);
$newFormGroup.append($newText);
$newText.after($newSubmit);
体力劳动多,
如何优雅地解决问题?
解决方案
#editCommentBtn
在您的未渲染代码中,我没有看到带有 Id 的元素。但是测试一下:
$(document).on("click","#editCommentBtn",function (e) {
e.preventDefault();
alert('button clicked');
});
通过这种方式,您将它们注入文档(并具有此 ID)的所有元素都将响应此单击功能。
推荐阅读
- android - Gradle 错误 HttpRequestException:无法使用 3.1.4 获取
- java - UVCCamera 不适用于特定设备
- python - 在 python 中使用 Text-Summarizer 进行文本摘要
- swift - Swift:在切换到控制器时清除缓存
- android - 库必须使用完全相同的版本规范(混合版本可能导致运行时崩溃)。找到版本 28.0.0-alpha1、26.1.0
- javascript - 在 Firefox 扩展中,moment.js 未在 chart.js 之前加载
- scala - 如何在 scala 中的 Dataframe 的字符串列上应用正则表达式模式?
- asp.net-core - 无法在.net核心中使用rabbitmq和masstransist处理多个请求
- ios - 无法在我的 iPhone X 上安装新的 Diawi 链接
- jquery - 根据月份名称对对象数组进行排序?