简体   繁体   English

表单提交后替换div

[英]Replace div after form submit

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#submit").click(function(){
    $("#p").replaceWith($("#p1"));
});
});
</script>
</head>
<body>
<div id="p">This is a paragraph.</div>
<div id="p1">Replacement</div>
<form action="" method="get">
<input type="submit" id="submit" name="submit" value="Search"/>
</form>
</body>
</html>

This code works fine until I put form action.. When I keep that submit in a form, this code does not work. 在我执行表单操作之前,此代码可以正常工作。 How can i replace that div after form submit. 表单提交后,我该如何替换该div。 Thanks. 谢谢。

You can try this one. 你可以试试这个。 Hope it helps! 希望能帮助到你!

 $(document).ready(function(){ $("#submit").click(function(event){ $("#p").replaceWith($("#p1").text()); return false; }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <div id="p">This is a paragraph.</div> <div id="p1">Replacement</div> <form action="" method="get"> <input type="submit" id="submit" name="submit" value="Search"/> </form> 

you need text method for that . 您需要使用text方法。 you were removing entire element before . 您之前已删除整个元素。 you need to remove only text value 您只需要删除文本值

 <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#submit").click(function(){ $("#p").replaceWith($("#p1").text()); }); }); </script> </head> <body> <div id="p">This is a paragraph.</div> <div id="p1">Replacement</div> <input type="submit" id="submit" name="submit" value="Search"/> </body> </html> 

指定用以下内容替换的内容:

 $(this).replaceWith("<div><p>Replacement</p></div>"); 

Form submission needs to be done using AJAX then only you can achieve this which you want to do. 表单提交需要使用AJAX完成,然后只有您才能实现所需的操作。

Otherwise the form will submit and page will refresh which will result to re initialization of script. 否则,表单将提交,页面将刷新,这将导致脚本重新初始化。

As Pooojaaqaa and Rayon mention the when the action attribute is set on the form tag, the form is submitted and the page is reloaded (even if action="#" ). 正如Pooojaaqaa和Rayon提到的那样,当在form标记上设置action属性时,将提交表单并重新加载页面(即使action="#" )。 To catch this action you need to catch the form's submit event, not the button's click event. 要捕获此操作,您需要捕获表单的submit事件,而不是按钮的click事件。 In the submit event handler you need to call preventDefault() on the event object passed into the handling function like below. submit事件处理程序中,您需要在传递给如下处理函数的事件对象上调用preventDefault()

<form id="frmSearch" action="#" method="get">
   <input type="submit" id="submit" name="submit" value="Search"/>
</form>
$("#frmSearch").submit(function(ev){
    ev.preventDefault();
    $("#p").replaceWith($("#p1").text());
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM