2012-04-12 83 views
0

我有一个JavaScript函数,可以为上传图片创建输入区域。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个inputfields。我从来没有使用JavaScript之前,不知道如何限制。

如果有人能告诉我如何认识到我真的很感激。非常感谢。

回答

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

多数民众赞成它。非常感谢。再见 – bonny 2012-04-12 09:01:21

0

在函数的开始,怎么算的项目很多都已经在那里,然后离开,如果有10我没有在这里使用“礼”,但你可以指望任何其他合适:

<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'); 
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>