您面临表单提交的默认行为,即导航到页面,在中指定
action
属性或重新加载当前页面,如果
行动
未指定。
您需要对代码进行以下更改才能修复此问题:
-
将提交处理程序注册修改为
form.setAttribute("onsubmit", "fo(event)");
-
改变
fo()
函数签名至
fo(event)
-
呼叫
event.preventDefault()
在…的结尾
if (cfm == false)
条件主体
因此,您的代码如下所示:
<html>
<body>
</body>
<script>
function give(){
form = document.createElement("FORM");
input = document.createElement("INPUT");
input.setAttribute("type", "submit");
input.setAttribute("value", "button");
form.setAttribute("id", "abc");
form.setAttribute("onsubmit", "fo(event)");
textarea = document.createElement("TEXTAREA");
textarea.setAttribute("id", "txt");
form.appendChild(input);
form.appendChild(textarea);
document.body.appendChild(form);
document.getElementById("abc").method = "post";
}
give();
function fo(event){
a = document.getElementById("txt").value;
cfm = confirm("Are you sure you want changes");
if (cfm == false ) {
div = document.createElement("DIV");
p = document.createElement("P");
ptxt = document.createTextNode("test");
p.setAttribute("id", "centr");
p.appendChild(ptxt);
div.appendChild(p);
document.body.appendChild(div);
event.preventDefault();
}
}
</script>
</html>