JQuery .clone()一个选择列表和ladbel,从数组加载标签

时间:2012-10-11 16:28:44

标签: jquery forms clone labels

我希望多次克隆两个表单元素。一个选择框和它的标签,但每次克隆元素我想提供一个数组的标签文本。我是以正确的方式接近这个还是我应该尝试不同的东西

<a href="#" onClick="createElement(5)">CLICK ME</a>
    <div id="selectBox1" class="cloned">
        <label>LABEL</label>
        <select name="name1" id="name1">
            <option>ONE</option>
            <option>TWO</option>
            <option>THREE</option>
        </select>
    </div>
</a>
function createElement(numElements) {
    //alert(numElements);

    //LABEL ARRAY
    var labels = [
        'Market',
        'Store',
        'Report Level',
        'Start Date',
        'End Date'];


    for (i = 0; i < numElements-1; i++) {                    
        var num = $('.cloned').length;//HOW MANY WE HAVE              
        var newNum = new Number(num + 1); //NUMBER OF ELEMENT BEING ADDED

        //LABEL
        //var newLabel = $('#selectLabel' + num).clone().attr('id', 'selectLabel' + newNum);//CLONE LABEL
        //newLabel.children(':first').attr('id', 'name' + newNum);//UPDATE NAME/ID

        //SELECTBOX
        var newElem = $('#selectBox' + num).clone().attr('id', 'selectBox' + newNum);//CLONE SELECTBOX
        newElem.children(':first').attr('id', 'name' + newNum).attr('name', 'name' + newNum);//UPDATE NAME/ID

        //$('#selectLabel' + num).after(newLabel);//INSERT THE NEW LABEL
        $('#selectBox' + num).after(newElem);//INSERT THE NEW ELEMENT
        }
    }

1 个答案:

答案 0 :(得分:0)

试试这个:

$(function() {
    //LABEL ARRAY
    var labels = [
        'Market',
        'Store',
        'Report Level',
        'Start Date',
        'End Date'
    ];
    var count = labels.length;

    $('#selectBox1').bind('click', function() {
        var self = $(this);
        var clones = $();
        var num = $('.cloned').length;

        $.each(labels, function(index, label) {
            var clone = self.clone();

            clone.attr({id: 'selectBox'+(++num)'});
            clone.find('label').attr({
                id: 'name'+num,
                name: 'name'+num
            }).text(label);

            clones = clones.add(clone[0]);
        });

        $('.cloned:last').after(clones);
    });
});