2013-03-14 30 views
0

我在我的网站中有一个Select菜单,位于表格内。分配选项以通过javascript选择输入

<select name = "menu" id="menu" > 
    <option>A</option> 
    <option>B</option> 
    <option>C</option> 
</select> 

我想要做一个JavaScript函数来添加另一个选择菜单,在表格下面的一行中有相同的选项。
我有这样的:

function addRow(tableID) { 
    var table = document.getElementById(tableID); 
    var rowCount = table.rows.length; 
    var row = table.insertRow(rowCount); 

    var cell1 = row.insertCell(0); 
    var element1 = document.createElement("select"); 
    element1.id = "id"; 
    cell1.appendChild(element1); 
} 

但我不知道在哪里添加的选项在这里。

我希望有人能帮助我。

+0

不使用document.createElement(“选项”)不工作?我从来没有使用过createElement选项 - 新选项(值,文本)是我曾经使用过的 – mplungjan 2013-03-14 22:02:48

回答

1

如果你想准确反正复制它,你也可以使用cloneNode()与此类似:

function addRow(tableID) { 
    var table = document.getElementById(tableID); 
    var rowCount = table.rows.length; 
    var row = table.insertRow(rowCount); 

    var cell1 = row.insertCell(0); 

    // Get a handle to the original select 
    var orgSelect = document.getElementById("menu"); 

    // Make a clone, using true to indicate we also want to clone child nodes 
    var dupSelect = orgSelect.cloneNode(true); 

    // Change any attributes of the new select 
    dupSelect.id = "id"; 

    // Append the new select 
    cell1.appendChild(dupSelect); 
} 

DEMO - 使用cloneNode()复制一个selectoptions


然后,您可以甚至使之成为一个功能调用,传递任何相关参数,与此类似:

function createClone(elementId, newId, includeChildNodes){ 
    var original = document.getElementById(elementId); 
    var duplicate = original.cloneNode(includeChildNodes); 

    duplicate.id = newId; 

    return duplicate; 
} 

// Call it like this 
var clonedElement = createClone('menu', 'newMenu', true); 
1

通过实例化一个新的Option对象,然后将它传递给select元素的add方法,可以将选项添加到select元素。

例如:

var opt = new Option("One", 1); 
element1.add(opt);