2012-03-13 62 views
0

我有一个fiddle如何在克隆的输入对象的值内打印嵌套数组?

代码:

//create array with values 
thisArray= ['',[]]; 
thisArray[0] = ['numbers',['one','two','three','four','five']]; 
// have a clean clone of input 
var newElem = $('#input').clone(); 

//search through aray and print the nested array inside the 
// value of the cloned input 
for(i = 0; i<thisArray[0][1].length; i++){ 

    $(newElem).val(thisArray[0][1][i]); 
    $('input.input').last().after(newElem); 
} 

条件:我不能改变所述阵列的HTML或布局。

问题:如何编辑for循环在克隆的输入字段中一个接一个地显示数组中的数字?所以最终的输出将是六个输入字段,每个输入字段除第一个输入字段外都有一个数字。

+0

您能否确认我的理解正确?你想克隆一个ID为#input的输入,并在页面上的类“.input”的最后一个输入之后插入该输入。你想在那个克隆的输入中显示“一个”,“两个”等,并且你希望在数字之间有一点点延迟,比如“one”....“two”....“three” 。主要是 – Niko 2012-03-13 01:08:05

+0

,我想要6个输入字段,每个字段除了第一个输入字段。我改变了小提琴,所以不会有超过一个元素具有相同的'身份证' – 2012-03-13 01:11:17

回答

0

你需要让五个人副本,以便插入五个新的输入:

//create array with values 
thisArray= ['',[]]; 
thisArray[0] = ['numbers',['one','two','three','four','five']]; 

var newElem; 

//search through aray and print the nested array inside the value of the cloned input 
for(var i = 0; i<thisArray[0][1].length; i++){ 
    newElem = $('.input').eq(0).clone(); // <-- cloning moved here! 
    newElem.val(thisArray[0][1][i]); 
    $('input.input').last().after(newElem); 
} 

http://jsfiddle.net/7NHXf/4/

+0

这是正确的,完美的作品,但我觉得这会比它可能慢。为什么我无法创建var newElem,然后编辑它并多次显示它与编辑? – 2012-03-13 01:24:20

+0

如果您克隆一次,则内存中只有一个输入元素。如果你想在屏幕上有多个输入,你只需要制作更多的副本。这就像:如果你买了一个芝士汉堡,那么你不能多吃一次芝士汉堡 - 如果你想吃不止一个芝士汉堡,你只需要购买更多。每个副本一次只能位于页面上的一个位置。 – Niko 2012-03-13 01:30:39

0

Woudn't这项工作?:

var numbers = ['one', 'two', 'three', 'four'], 
    $field = $('.field'), 
    newFields = []; 

for (var i = 0, len = numbers.length; i < len; i++) { 
    var field = '<input type="text" value="'+ numbers[i] +'" />'; 
    newFields.push(field); 
} 

$(newFields.join('')).insertAfter($field); 

http://jsfiddle.net/elclanrs/7NHXf/9/