所以这就是我要做的:在我的网页中,我有很多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() 来处理每个表单的寻址会更好吗?
代码看起来差不多,假设$("#commentreply").each(function()
是临时的,您将选择多个表单。
但目前该表格正在发布,因为
$(this).submit(function() {
event.preventDefault();
你没有阻止任何事情。
$(this).submit(function(event) { // <-- You need to declare event
event.preventDefault();
要回答第二个问题,如果可以使用每个代码,请使用每个代码而不是重复代码。
此外,如果有许多表单,则在用户使用表单保存之前,不应绑定事件,从而减慢页面速度。
重新错误Uncaught TypeError: Cannot call method "createDocumentFragment"
如果不进行检查,这可能是因为:
posting.done(function(data) {
$(this).replaceWith("(HTML content to replace form)");
}).error(function(){
$(this)
现在是posting
,而不是形式。
在此行之后插入
$("#commentreply").each(function() {
var $form = $(this);
并替换
$(this).replaceWith("(HTML content to replace form)");
跟
$form.replaceWith("<div>(HTML content to replace form)</div>");
使其成为 HTML 元素,而不仅仅是字符串。
我会使用另一种方法:
当提交触发器→替换父表单时:
$('form').submit(function(event){
event.preventDefault();
/* Fire your validation and $.post */
$(this).replaceWith("<div>new HTML content to replace with</div>");
});
您甚至可以对其进行动画处理:
$('form').submit(function(event){
event.preventDefault();
/* Fire your validation and $.post */
$(this).slideUp(function(){
$(this).replaceWith(
$("<div style='display:none'>new HTML content to replace with</div>").slideDown()
);
});
});
它未经测试。