名单选项列表保持相乘

时间:2015-10-07 11:30:09

标签: jquery

function addteamSection() {
    var teamList = $('#team_table');
    var team_temp = '';
    var size_temp = ["20", "30", "40", "50", "60"];

    teamList.append("<tr><td><input class='name' type='text' name='player_name' /></td><td><input class='number' type='text' name='player_number' /></td><td><select class='sizeList'></select></td></tr>");

    for (var s = 0; s < size_temp.length; s++) {
        var sizeList = $('.sizeList');
        team_temp += "<option value=" + size_temp[s] + ">" + size_temp[s] + "</option>";
    }

    sizeList.append(team_temp);

}

我的目的是通过点击按钮创建一个添加名称列表,它将有年龄选择供用户选择,但我的选项保持相乘,因为我有相同的类名,但我想如何添加到选择不使用任何id并确保它没有乘法。

Demo

保持点击几次添加并检查第一个选项,重复一遍。

1 个答案:

答案 0 :(得分:0)

将你的字符串建筑分开。

Working fiddle

function addteamSection(){
        var teamList = $('#team_table');
        var team_temp = '';
        var size_temp = ["20", "30", "40", "50","60"];

        var rowString = "<tr><td><input class='name' type='text' name='player_name' /></td><td><input class='number' type='text' name='player_number' /></td><td>"
        var selectString = "<select class='sizeList'>"

        /* Instead of using var sizeList = $('.sizeList'); to select the new dropdown
           (which won't work anyway because your new element hasn't been added to the 
           DOM yet.) You can manually build the select box, append the options to it
           and then append it to your DOM element.*/

        for(var s = 0; s < size_temp.length; s++){

            selectString += "<option value="+size_temp[s]+">"+size_temp[s]+"</option>";
        }

    selectString+="</select></td></tr>";
    rowString+=selectString;
    teamList.append(rowString);


    }
addteamSection();

$('#addf').click(function() {
    addteamSection();
});