我有一个javascript函数,可以创建用于上传图像的输入字段。
我有这段代码:
<script type="text/javascript">
function add_input(){
var wo = document.getElementById('wo');
var li = document.createElement('li');
var input = document.createElement('input');
input.type = 'file';
input.name = 'image[]';
li.appendChild(input);
li.appendChild(document.createTextNode(' '));
var button=document.createElement('input');
button.type = 'button';
button.className = 'button small';
button.onclick=function(){delete_input(this);};
button.value = 'delete';
li.appendChild(button);
wo.appendChild(li);
}
function delete_input(feld){
feld.parentNode.parentNode.removeChild(feld.parentNode);
}
</script>
现在我的问题是我想创建最多10个输入字段。我之前从未使用过javascript,也不知道如何限制它。
如果有人能告诉我如何意识到我真的很感激。非常感谢。
答案 0 :(得分:3)
修改您的脚本,使其具有:
<script type="text/javascript">
var max = 10;
var current = 0;
function add_input(){
if(current < max){
current++;
//...do everything in here for append
}
}
function delete_input(feld){
if(current > 0){
current--;
feld.parentNode.parentNode.removeChild(feld.parentNode);
}
}
</script>
答案 1 :(得分:0)
在功能开始时,计算已经存在的项目数量,如果有10项则离开。我在这里使用'li'做了,但你可以计算其他任何合适的项目:
<script type="text/javascript">
function add_input(){
var wo = document.getElementById('wo');
var objList = wo.getElementsByTagName('li');
var soFar = objList.length;
if (soFar > 9) {
alert ("yikes");
return;
}
var li = document.createElement('li');
var input = document.createElement('input');
答案 2 :(得分:0)
最好定义一个全局计数器,根据你给出的代码,这里是修改:
<script type="text/javascript">
var counter = 0;
function add_input(){
if (counter >= 10)
return false;
var wo = document.getElementById('wo');
var li = document.createElement('li');
var input = document.createElement('input');
input.type = 'file';
input.name = 'image[]';
li.appendChild(input);
li.appendChild(document.createTextNode(' '));
var button=document.createElement('input');
button.type = 'button';
button.className = 'button small';
button.onclick=function(){delete_input(this);};
button.value = 'delete';
li.appendChild(button);
wo.appendChild(li);
counter ++;
}
function delete_input(feld){
feld.parentNode.parentNode.removeChild(feld.parentNode);
counter --;
}
</script>