2014-05-06 40 views
-2

所以,我已經試過一堆東西,但沒有建立一種解決方法與此在JavaScript動態添加表單元素在IE/Mozilla的

我有這樣的代碼能正常工作在Chrome。但它不適用於Mozilla或IE,在控制檯中它不會顯示任何錯誤。它只是不起作用。

<?php 

echo"<script>alert('okay');</script>"; 

?> 


<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> 
<head> 
    <meta charset="UTF-8" /> 
</head> 
    <script type="text/javascript" LANGUAGE="JavaScript1.3"> 
     function name3() { 
      var abc = document.createElement("FORM"); 
       //abc.setAttribute("method","POST"); 
      abc.method = "POST"; 
      abc.action = "http://localhost/2.php"; 
      var a = document.createElement("INPUT"); 
       /*a.setAttribute("type","text"); 
       a.setAttribute("name","a"); 
       a.setAttribute("value","abc");*/ 
      a.name = 'a'; 
      a.value = "abc"; 
      abc.appendChild(a); 
      abc.submit(); 
     } 
    </script> 
    <input type = "button" onclick = "name3();" value = "click"> 
</html> 

相反a.name的,我也用a.setAttribute嘗試,但仍然沒有工作

請幫助!謝謝:)

+0

你沒有標籤。它可能會導致問題(因爲DOM無效) – Gwenc37

回答

0

你應該將表格附加到正文,然後後者將其刪除一次。目前,您並未將表單添加到DOM。它實際上需要在DOM中以頁面加載方式發送。

完整代碼

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> 

<head> 
    <meta charset="UTF-8" /> 
    <script type="text/javascript"> 
     function name3() { 
      var form = document.createElement("FORM"); 
      form.method = "POST"; 
      form.action = "http://localhost/2.php"; 
      var a = document.createElement("INPUT"); 
      a.name = 'a'; 
      a.value = "abc"; 
      form.appendChild(a); 

      //Apend form to body 
      document.getElementsByTagName('body')[0].appendChild(form); 

      //Submit form 
      form.submit(); 

      // But once the form is sent, it's useless to keep it. 
      document.getElementsByTagName('body')[0].removeChild(form); 
     } 
    </script> 
</head> 

<body> 
    <input type="button" onclick="name3();" value="click" /> 
</body> 

</html> 
0

你應該首先將新元素添加到DOM樹,然後提交表單。如果你不想顯示它們,你可以添加樣式來隱藏元素。

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> 
<head> 
    <meta charset="UTF-8" /> 
</head> 
<script type="text/javascript"> 
    function name3() { 
     var abc = document.createElement("FORM"); 
      //abc.setAttribute("method","POST"); 
     abc.method = "POST"; 
     abc.action = "http://localhost/2.php"; 
     var a = document.createElement("INPUT"); 
      /*a.setAttribute("type","text"); 
      a.setAttribute("name","a"); 
      a.setAttribute("value","abc");*/ 
     a.name = 'a'; 
     a.value = "abc"; 
     abc.appendChild(a); 

     document.getElementById("body").appendChild(abc); 
     abc.submit(); 
    } 
</script> 
<body id="body"> 
    <input type = "button" onclick = "name3();" value = "click"> 
</body>