首页 > 解决方案 > 从 $().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> &nbsp
    <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);

体力劳动多,
如何优雅地解决问题?

标签: javascriptjquery

解决方案


#editCommentBtn在您的未渲染代码中,我没有看到带有 Id 的元素。但是测试一下:

$(document).on("click","#editCommentBtn",function (e) {
    e.preventDefault();
    alert('button clicked');
});

通过这种方式,您将它们注入文档(并具有此 ID)的所有元素都将响应此单击功能。


推荐阅读