1

如何从第一个选项中获取动态创建的选择的所有选项,我尝试使用 jquery 但没有工作:

 for( j = 0; j < i; j++)
     $('#s1 option').clone().appendTo(IS+j);

HTML 文件:

<input type="button" value="Add" id="btn1" OnClick="f('dv1');">
<div id="dv1">
    <select id="s1" name="select1">
        <option>
            1
        </option>

        <option>
            2
        </option>
    </select>
</div>

<script type="text/javascript" src="js/functions.js"></script>

函数.js

var i = 1;
function f(x){
    var y = document.createElement('div');
    y.innerHTML = '<br><Select id="IS"'+i+ 'name="NAME"'+i+' > </Select>';
    document.getElementById(x).appendChild(y);
    i++;
}
4

2 回答 2

1

由于您似乎正在创建多个选择对象,因此您需要修复您的 jquery 选择器和您为选择生成的 id。首先,$('#s1 option').clone().appendTo(IS+j); 应改为:

$('#s1 option').clone().appendTo('#IS' + j);

其次,y.innerHTML = '<br><Select id="IS"'+i+ 'name="NAME"'+i+' > </Select>'; 应改为:

y.innerHTML = '<br /><select id="IS'+i+ '" name="NAME'+i+'"></select>';

编辑

如果您只是尝试克隆原始下拉列表,则以下内容应该适合您:

function f(x){
    // Create new select within its own div
    var y = document.createElement('div');
    y.innerHTML = '<br /><select id="IS'+i+ '" name="NAME'+i+'"></select>';
    document.getElementById(x).appendChild(y);

    // Fill new select with the options from the original
    $('#IS' + i).html($('#s1').html());

    i++;
}

现场演示

于 2012-06-08T00:25:15.303 回答
0

如果您出于任何原因需要迭代选项以进行更改,这是另一种方法

var newSelect = $("<select />");

$.each(primarySelect.options, function (i, opt)
{
   $(newSelect).append($('<option></option>', { 
       value: opt.value, text: opt.text, selected: opt.selected }));
});

JS Fiddle Live 版本

一定不要使用$(primarySelect.options).each(...),因为这在 IE 中无法正常工作。


另请参阅:使用 jQuery 从数组中添加选项的最佳方法是什么?

于 2013-02-05T01:22:48.317 回答