我有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 :(得分: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);
}
答案 1 :(得分:0)
这不行吗?:
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);