簡體   English   中英

如何使用jQuery從數組動態創建輸入元素?

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

我正在動態創建輸入元素。 我有一個包含 n 個元素的數組。 我需要使用 Jquery 創建 n 個輸入框,並將數組的每個元素的值放入一個單獨的輸入框。

我正在使用 .trigger("click") 函數來模擬點擊。 此外,我嘗試尋找解決方案,但找不到滿意的結果。 因此,我決定提出這個問題。 我查看了 .map() Jquery 函數。 .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