2016-05-14 42 views
2

我的代码的一部分有问题。我尝试使用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> 
+0

在函数中使用它们之前是否在其他地方声明了变量(a,cfm,div,p osv)? –

+0

不幸的是,没有。 – s0lw

+0

你可以发布你的电话和一些你的HTML吗? –

回答

0

你面对提交表单的默认行为,这是浏览到另一个页面,在action属性指定的或者未指定action重新加载当前页面。

你需要做以下更改代码,以解决这个问题:在if (cfm == false)条件的主体的末尾

  1. 修改提交处理登记form.setAttribute("onsubmit", "fo(event)");
  2. 变化fo()函数签名fo(event)
  3. 呼叫event.preventDefault()

所以你的代码看起来像这样:

<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> 
+0

哇,现在它工作!非常感谢 – s0lw

+0

@ s0lw没问题)只需将答案标记为已接受 – mshipov

相关问题