【发布时间】:2016-05-14 18:12:55
【问题描述】:
我的代码的某些部分有问题。我尝试使用 JavaScript 创建“DIV”和“P”标签,但只有当我将代码放在函数之外时它才有效(函数称为“fo”) .当你点击按钮时,会出现一个对话框,如果你点击取消,appendChild方法应该把“div”和“p”标签放在“body”里面。
我应该添加 p 标签中的文本可以在屏幕上短暂看到,然后突然消失。我的浏览器是谷歌浏览器。
<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()");
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(){
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);
}
}
/*When this part of code is outside function fo() , appendChild works correctly
div = document.createElement("DIV");
p = document.createElement("P");
ptxt = document.createTextNode("Outside the function it works");
p.setAttribute("id", "centr");
p.appendChild(ptxt);
div.appendChild(p);
document.body.appendChild(div);
*/
</script>
</html>
【问题讨论】:
-
在函数中使用变量(a、cfm、div、p osv)之前,您是否在其他地方声明了它们?
-
很遗憾,没有。
-
您可以发布您的电话和一些 HTML 吗?
-
如何调用函数 fo()?如果内容出现又消失,听起来好像它可能会被调用以响应表单提交,这会重新加载页面。
-
您收到的实际错误是什么
标签: javascript html appendchild