繁体   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