javascript - 使用JS动态添加下拉列表表

标签 javascript html

我想动态创建一个下拉列表表。 这是程序: 1) 在表格第一行的第一个单元格中出现一个选择框,其中包含几个选项。 2) 当用户点击一个选项时,另一个选择框出现在第一行的第二个单元格中。 3) 在第三个单元格中,必须有一个按钮,单击该按钮将添加一个带有选择框的新行,如第 1 点所述。

<html>
<head>
    <title>Search</title>
    <script type="text/javascript">
        var noRows = 1;
        function func(){
            var t = document.getElementById('searchTable');
            var r = table.insertRow(noRows);
            var col = row.insertCell(0);
            var colNames = document.createElement('select');
            colNames.id = 'colNames0';
            colNames.name = 'colNames' + noRows;
            colNames.onchange = populate;
            colNames.options[0] = new Option('Select','');
            for(var i = 0;i < cols.length;++i){
                colNames.options[i+1] = new Option(cols[i],ids[i]);
            }
            colCell.appendChild(colNames);
        }
        function populate(){
            var sel = document.getElementById("colNames" + noRows);
            var col = sel.options[sel.selectedIndex].id;
            if(col == "int"  || col == "date" || col == "time")
                populateInt();
            else
                populateString();
        }
    </script>
</head>
<body onload="func();">
    <table id="searchTable">
    </table>    
</body>

这是我开始的代码。我在第一行的第一个单元格中动态创建了选择框,但无法获取所选选项并创建进一步的选择列表。

最佳答案

我没有看到 int、date 或 time 作为 id 分配给那里的任何选项和其他东西

var col = sel.options[sel.selectedIndex].id;

你可以像下面这样写而不是这一行

var col = sel.options[sel.selectedIndex].getAttribute('id');

关于javascript - 使用JS动态添加下拉列表表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41764700/

相关文章:

javascript - 如何在父兄弟跨度上设置文本

javascript - ChartJS BoxWidth 不起作用

html - 一流选择器中的 css 类

jquery - 使用两个子菜单创建菜单

Javascript 验证无法正常工作

javascript - 如何使用 jQuery 重置 CSS?

javascript - 作为对象属性名称传递给函数的字符串

javascript - capybara 无法点击按钮

html - IE7 和 IE8 可见性问题

HTML/inputs 元素在同一行