【问题标题】:How to create input elements dynamically from an array with jQuery?如何使用 jQuery 从数组中动态创建输入元素?
【发布时间】:2017-02-05 10:37:20
【问题描述】:

我正在动态创建输入元素。我有一个包含 n 个元素的数组。我需要使用 Jquery 创建 n 个输入框,并将数组的每个元素的值放入单独的输入框中。

我正在使用 .trigger("click") 函数来模拟点击。另外,我尝试寻找解决方案,但找不到满意的结果。因此,我决定提出这个问题。我查看了 .map() Jquery 函数。 .map().get 函数从动态创建的输入框中返回数组。

【问题讨论】:

标签: javascript jquery html arrays


【解决方案1】:

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 2019-01-02
    • 1970-01-01
    相关资源
    最近更新 更多