所以这就是我想要做的:在我的网页中,我有很多 HTML 表单。如果提交了任何单个表单,我希望将整个表单替换为某些内容。但是,我无法做到这一点。
下面是我的 JavaScript 代码:
$("#commentreply").each(function() {
    var replace = false;
    $(this).submit(function() {
        // http://stackoverflow.com/q/16323360/1222411
        event.preventDefault();
        var url = $(this).attr('action');
        var nameValue = $(this).find('input[name="name"]').val();
        var commentValue = $('#commentEntry').val();
        var projectValue = $(this).find('input[name="project"]').val();
        var idValue = $(this).find('input[name="id"]').val();
        var posting = $.post(url, {
            project : projectValue,
            id : idValue,
            name : nameValue,
            comment : commentValue
        });
        posting.done(function(data) {
            $(this).replaceWith("(HTML content to replace form)");
        }).error(function(){
            alert("An error occurred. Be sure you entered a name and comment and try again");
        });
    });
});
这个想法是以下 HTML 代码:
<form id="commentreply" name="reply" action="/lib/comments/addComment.php" method="post">
    <input type="hidden" name="project" value="project">
    <input type="hidden" name="id" value="-1">
    Name:<input type="text" id="nameEntry" name="name" size="100"><br>
    Comment:<br><textarea id="commentEntry" name="comment" size="255">
        Enter comment here</textarea><br>
    <input type="submit" value="Submit">
</form>
当点击提交按钮时会变成这样:
(HTML content to replace form)
有什么建议吗?将 JavaScript 附加到每个表单而不是使用 .each() 来处理每个表单的寻址会更好吗?