簡體   English   中英

如何從JS函數獲取動態值

[英]How to get dynamic values from JS function

我有此功能,它會根據用戶的選擇生成許多輸入:

        // 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"));

  }
  }

而且效果很好。 但是,我將需要在其他功能上使用用戶引入的值。 我該如何正確地稱呼他們?

您將需要為正在創建的每個輸入控件分配某種標識符(以在以后引用它們)。 一種非常簡單的方法是為每個對象分配一個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;
}

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

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

現在您可以遍歷“ inputsNumber”並檢索值

也可以使用通配符過濾querySelector,以檢索名稱以單詞開頭的元素,方法是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM