简体   繁体   English

如何使用jQuery从数组动态创建输入元素?

[英]How to create input elements dynamically from an array with jQuery?

I am creating input elements dynamically.我正在动态创建输入元素。 I have an array that has n number of elements.我有一个包含 n 个元素的数组。 I need to create n input boxes using Jquery and put the value of each element of an array into a separate input box.我需要使用 Jquery 创建 n 个输入框,并将数组的每个元素的值放入一个单独的输入框。

I am using the .trigger("click") function to simulate a click.我正在使用 .trigger("click") 函数来模拟点击。 Additionally, I tried looking for solution, but could not find a satisfactory result.此外,我尝试寻找解决方案,但找不到满意的结果。 Therefore, I decided to put this question.因此,我决定提出这个问题。 I looked at .map() Jquery function.我查看了 .map() Jquery 函数。 The .map().get function returns the array from dynamically created input boxes. .map().get 函数从动态创建的输入框返回数组。

 var values = [1, "hello", 1.6, "some other value"]; // the container you want to append the inputs to var $container = $("#container"); values.forEach(function(value) { // create the an input var $input = $("<input/>"); // change it's properties (if you want to) // $input.addClass("someClass"); // $input.attr("name", "someName"); // $input.attr("id", "someID"); // ... // set its value $input.val(value); // append it to the container $container.append($input); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM