2010-10-20 73 views
0

好吧,所以我有一個腳本,當你點擊一個鏈接它動態地添加一個表單字段是有可能的,所以當它被提交時,它會去「example.com?7」(7由於7檔) 我的意思是,如果我點擊5次,有5個文件字段和我選擇5個文件,我可以讓操作鏈接mysite.php 5使用javascript來改變提交鏈接

這裏是腳本:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Untitled Document</title> 
<script type="application/javascript"> 

function add(){ 
var field = document.createElement('input'); 
field.setAttribute("type", "file"); 
field.setAttribute("name", "yo"); 
document.getElementById('myform').appendChild(field); 
} 

</script> 
</head> 

<body> 
<form id="myform" name="form1" enctype="multipart/form-data" method="post" action=""> 
    <p>File: 
    <input type="file" name="hello" id="hello" /> 
    </p> 
    <p> 
    <input name="submit" type="submit" value="Submit" /> 
    </p> 
</form> 

<a href="#" onclick="add()">Click Here</a> 
</body> 
</html> 

非常感謝!

回答

0

我會保持簡單並跟蹤您添加了多少個文件字段。每次添加新文件字段時只更新網址。

var numFileElements = 1; 
function add(){ 
    var field = document.createElement('input'); 
    field.setAttribute("type", "file"); 
    field.setAttribute("name", "yo"); 
    var myForm = document.getElementById('myform'); 
    myForm.appendChild(field); 
    ++numFileElements; 
    myForm.setAttribute('action', '?'+ numFileElements); 
} 
+0

工作就像一個魅力。非常感謝。 – DonJuma 2010-10-20 16:09:01

0

只需在表單中保留一個額外的隱藏字段(稱之爲「count」),並在該腳本添加其他文件輸入時增加其值。

+0

我只是(document.write)還是什麼。我對JavaScript很陌生。 – DonJuma 2010-10-20 14:12:38

0

有點像?

function doSubmit() { 
    var myForm = document.getElementById('myForm'); //Get myForm 
    var childNodes = myForm.childNodes; //Count child nodes 
    var fields = 0; 
    for (var node in childNodes) { 
     if (childNodes[node].tagName == 'P') fields++; 
    } 
    myForm.setAttribute('action', 'mysite.php?'+fields); 
} 

它計數直接在myForm下的所有P元素。不完美,但它應該工作!只需添加一個onsubmit='doSubmit();

1

我建議給新增加的領域類=「classX」,當你提交表單算不與指定類的元素與getElementsByClassName方法

我覺得比遞增的每個值更簡單添加一個字段的時間