2017-08-28 43 views
0

我有這個功能,產生了許多基於用戶的選擇輸入:如何從JS函數獲取動態值

 // Number of inputs to create 
     var number = document.getElementById("cantidadArreglos").value; 
     // Container <div> where dynamic content will be placed 
     var container = document.getElementById("container"); 
     // Clear previous contents of the container 
     while (container.hasChildNodes()) { 
      container.removeChild(container.lastChild); 
     } 
     for (i=0;i<number;i++){ 
      // Append a node with a random text 
      container.appendChild(document.createTextNode("Arreglo #" + (i+1))); 
      // Create an <input> element, set its type and name attributes 
      var input = document.createElement("input"); 
      input.type = "number"; 
      input.name = "arreglo" + i; 
      container.appendChild(input); 
      // Append a line break 
      container.appendChild(document.createElement("br")); 

    } 
    } 

而且它完美的作品。但是,我需要使用用戶在其他函數中引入的值。我如何正確地打電話給他們?

+1

請創建一個[最小,完整,可驗證](https://stackoverflow.com/help/mcve)例子。你的代碼拋出錯誤。 – lumio

+0

此代碼是從這裏的帖子中提取的,並生成我想要的輸入,所以我不明白你的意思是「拋出錯誤...」。我的問題很簡單:如何在另一個函數中調用/使用這些相同的輸入?我應該爲每個輸入創建一個ID嗎?然後什麼? – eduroc92

+0

這是你發佈的所有代碼嗎? – lumio

回答

1

您將需要爲您正在創建的每個輸入控件(稍後參考它們)分配某種標識符。一個非常簡單的方式做,這是分配他們每人一個ID:

for (i=0;i<number;i++) { 
    // Append a node with a random text 
    container.appendChild(document.createTextNode("Arreglo #" + (i+1))); 
    // Create an <input> element, set its type and name attributes 
    var input = document.createElement("input"); 
    input.type = "number"; 
    input.name = "arreglo" + i; 
    //assign identifier here 
    input.id= "arreglo" + i; 
    container.appendChild(input); 
    // Append a line break 
    container.appendChild(document.createElement("br")); 
} 

然後,其他地方在你的代碼,你可以使用你剛纔創建的索引參考值:

function getValForId(var id) { 
    return document.getElementById("arreglo" + id).value; 
} 
1

你可以使用document.querySelectorAll('input [type =「number」]')將檢索頁面的所有類型編號的輸入(如果您需要排除一些,只需添加一個類並將其添加到querySelector)

var inputsNumber = document.querySelectorAll('input[type="number"]'); 

現在,您可以遍歷「inputsNumber」和檢索值

也可以使用通配符檢索其名稱中使用了字開頭的元素過濾querySelector:

document.querySelectorAll('[name^=arreglo]'); 
+0

如果使用'getElementByTagName',則需要指定一個標記名稱,而不是'name'屬性。 –

+0

@MattSpinks糟糕!與ID混淆,編輯。 – Sergio10