【问题标题】:Assign options to select input through javascript分配选项以通过 javascript 选择输入
【发布时间】:2013-03-03 11:51:53
【问题描述】:

我的站点中有一个Select 菜单,位于表格内。

<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);
}

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

我希望有人可以帮助我。

【问题讨论】:

  • document.createElement("option") 不起作用吗?我从未将 createElement 用于选项 - new Option(value,text) 是我以前使用的

标签: javascript html select options appendchild


【解决方案1】:

您可以通过实例化一个新的Option 对象,然后将其传递给选择元素的add 方法来为选择元素添加选项。

例如:

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

【讨论】:

    【解决方案2】:

    如果你想完全复制它,你也可以使用类似这样的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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多