2016-05-14 30 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

相關問題