我的代码的一部分有问题。我尝试使用JavaScript创建“DIV”和“P”标记,但它只在将代码放在函数外部时才起作用(函数名为“fo”)。当你点击按钮时,会出现一个对话框,如果你点击取消,appendChild方法应该在“body”中放入“div”和“p”标签。appendChild在函数外部工作,但不在
我应该补充说,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)? –
不幸的是,没有。 – s0lw
你可以发布你的电话和一些你的HTML吗? –