如何动态生成多个输入字段jQuery而不覆盖最后一个

时间:2013-08-27 15:01:42

标签: jquery variables loops dynamic foreach

所以我正在处理一些jQuery代码,以便在页面上显示新的手机数据。

到目前为止,一切正常,除了最后一个电话号码是唯一一个无论我有多少电话号码都要显示的电话号码。我发现它是因为我的$('.new_option').append(inputphone);覆盖了最后一个。

这是jsFiddle (不完全相同的代码,因为我没有数据库对象,但会产生同样的问题):http://jsfiddle.net/leongaban/dvYMb/

变量(带标签+输入的HTML):

var inputphone = $("<li><label></label><br/><input type='tel' pattern='[0-9]{10}' class='added_phone' name='' value='' autocomplete='off' maxlength='20' /></li>");

HTML DOM:

<li>
    <ul class="new_option">
    </ul>
</li>

每个循环:

$(profileData.phones).each(function(i) {
    console.log(' ');
    console.log('Phones: '+i);
    console.log(profileData.phones[i].label);
    $('.new_option').append(inputphone); //<-- The Issue
    $('.added_phone').parent().find('label').text(profileData.phones[i].tag);
    $('.added_phone').attr('id', "added_"+profileData.phones[i].tag+"phone" + i);
    $('.added_phone').attr('value', profileData.phones[i].label);
});

控制台:
enter image description here

页面结果:
enter image description here

我的问题是如何让这一行动态生成具有唯一ID的新字段?

$('.new_option').append(inputphone); 

here周围搜索我看到有人说使用了一个对象,但尚未成功使用该方法。

你会如何处理?

2 个答案:

答案 0 :(得分:1)

来自CSS-Tricks Javascript form post

的论坛海报的回答

CodePen http://codepen.io/ggilmore/pen/f3a88dd68a7b1d101712b75318925198

var inputphone = "<label></label><br/><input type='tel' pattern='[0-9]{10}' class='added_phone' name='' value='' autocomplete='off' maxlength='20' />";

var profileData = "Text for input";
var currentListItem;

for (var i = 0, max = 2; i < max; i++) {
    $('.new_option').append('<li class="input-'+i+'" />');

    currentListItem = $('.input-'+i);
    currentListItem
        .append(inputphone)
        .find('label').text(profileData)

    currentListItem
        .find('.added_phone').attr('id', "added_phone" + i).attr('value', profileData);
}

另请注意:这适用于我在jsFiddle和CodePen中创建的简单基本示例,但是在进一步开发时,它仍然会导致我的phoneData对象出现同样的问题。

走另一条路。获取通过Python显示的电话号码(我本来应该做的,然而我的前端开发人员喜欢jQuery)我希望这有助于某人!

答案 1 :(得分:0)

问题是由于您填写了ul并且之后没有重置它而引起的。

以下是您需要做的事情:

$(profileData.phones).each(function(i) {
    console.log(' ');
    console.log('Phones: '+i);
    console.log(profileData.phones[i].label);
    $('.new_option').append(inputphone);
    // Reset the ul now and add a new empty ul
    $('.new_option').attr('class', 'ul_added');
    var p = $('.added_phone').parent().parent(); // This is the li above the ul
    p.append('<ul class="new_option"></ul>');
    // Set the values
    $('.added_phone').parent().find('label').text(profileData.phones[i].tag);
    $('.added_phone').attr('id', "added_"+profileData.phones[i].tag+"phone" + i);
    $('.added_phone').attr('value', profileData.phones[i].label);
});