jQuery jquery循环创建元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2546372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:45:56  来源:igfitidea点击:

jquery loop to create elements

jqueryloops

提问by Andy

I have had no luck with this task so far so grateful for any help.

到目前为止,我对这项任务的运气不佳,非常感谢您的帮助。

I have an html form, in which there is a small select menu (1-10) ie

我有一个 html 表单,其中有一个小的选择菜单 (1-10) 即

<select>
    <option value = '1'>1</option>
    <option value = '2'>2</option>
    ...
    <option value = '10'>10</option>
</select>

depending on what value is selected i would like jquery to create (or remove) that number of input text boxes (with different names and id's). eg if 2 was selected these inputs would be created:

根据选择的值,我希望 jquery 创建(或删除)该数量的输入文本框(具有不同的名称和 ID)。例如,如果选择了 2,将创建这些输入:

<input type = 'text' name = 'name1' id = 'id1' />
<input type = 'text' name = 'name2' id = 'id2' />

i look forward to your no doubt simple and elegant solutions! andy

我期待着您无疑简单而优雅的解决方案!安迪

回答by Tatu Ulmanen

Something like this:

像这样的东西:

$('select').change(function() {
     var num = parseInt($(this).val(), 10);
     var container = $('<div />');
     for(var i = 1; i <= num; i++) {
         container.append('<input id="id'+i+'" name="name'+i+'" />');
     }
     $('somewhere').html(container);
});

回答by Alistair

To slightly modify Tatu's answer,

稍微修改大图的答案,

$('select').change(function() {
 var num = parseInt($(this).val(), 10);
 var container = $('<div />');

 for(var i = 1; i <= num; i++) {
     $('<input />', {
         id: "id" + 1,
         name: "name" + 1
     }).appendTo(container);
 }

 $('somewhere').html(container);
 });

This way is faster and a bit easier to read. The reason it is faster is because jQuery heavily caches creating elements. It caches "<input />" the first time and then just uses the cached object to create more of them. It can do this because the text doesn't change. However, it can't do this caching with append (or html not created by calling the main jquery function $ AFAIK) since due to the ids they are unique each loop. See John Resig's 'Things you might not know about jQuery' speech for info on this.

这种方式更快,更容易阅读。它更快的原因是因为 jQuery 大量缓存创建元素。它第一次缓存“<input />”,然后只使用缓存的对象来创建更多的对象。它可以这样做,因为文本不会改变。但是,它无法使用 append(或不是通过调用主 jquery 函数 $ AFAIK 创建的 html)进行缓存,因为由于 id,它们在每个循环中都是唯一的。有关这方面的信息,请参阅 John Resig 的“关于 jQuery 你可能不知道的事情”演讲。

回答by kbro

This uses $.map()to iterate over an array using the index to emulate the "0..N" range operator of languages like Perl and PHP. Since $.map()returns an array of the return values of each call to the callback function, we can pass this straight to $().html()to set the content of the parent element. Neat?

这用于$.map()使用索引迭代数组以模拟 Perl 和 PHP 等语言的“0..N”范围运算符。由于$.map()每次调用回调函数都会返回一个包含返回值的数组,因此我们可以直接将$().html()其传递给以设置父元素的内容。整洁的?

Just make sure you declare the callback function's 'object' and 'index' parameters in the correct order - they're the opposite way around to $.each()!

只需确保以正确的顺序声明回调函数的“对象”和“索引”参数 - 它们与$.each()!

HTML

HTML

<div id='container'></div>

JS

JS

const HOW_MANY = 10;

$('#container').html(
  $('<select/>', { id: 'selection' }).html(
    $.map(Array(HOW_MANY), function(o,i) {
      i++;  // because array indices run from 0
      return $('<option/>', { value: i }).text(i);
    }) // map
  ) // <select/>
);

FIDDLE

小提琴

https://jsfiddle.net/kmbro/xxtbjgzo/

https://jsfiddle.net/kmbro/xxtbjgzo/

回答by Matt

<select>
    <option value = '1'>1</option>
    <option value = '2'>2</option>
    ...
    <option value = '10'>10</option>
</select>
<div id="container">
</div>

For your markup.

为您的标记。

Then

然后

$('select').bind('change', function () {
    var val = parseInt($(this).val(), 10) + 1,
        str = '';

    for (var i=1; i<val;i++) {
        str += '<input type="text" name="name' + i + '" id="id' + i + '"/>';
    }

    $('#container').html(str);
});