2012-04-12 98 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>