繁体   English   中英

将项目添加到表格-HTML / CSS / JS

[英]Add Item to Table - HTML/CSS/JS

假设我有一个下拉列表(或组合框),并且其中包含内容列表。 从列表中选择一件事后,它将自动添加到表中。 我该怎么做? 可能只有HTML / JS吗?

落下:

<select class="combobox form-control" style="display: none;">
    <option value="" selected="selected">Point Guard</option>
    <option value="CP3">Chris Paul (93)</option>
 </select>

表:

<table class="table">
    <thead>
      <tr>
        <th>Position</th>
        <th>First Name</th>
        <th>Last Name</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>Mark</td>
        <td>Otto</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Jacob</td>
        <td>Thornton</td>
      </tr>
      <tr>
        <td>3</td>
        <td>Larry</td>
        <td>the Bird</td>
      </tr>
    </tbody>
</table>

谢谢。

使用jQuery:

$('.combobox').change(function(e) {

   var selectedVal = $(this).val();
   $('.table').append('<tr><td>' + selectedVal + '</td></tr>');

});

希望您能明白。

请尝试使用以下代码段。

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script>
        $(document).ready(function () {
            $(".combobox").change(function () {
                var temp1 = $(".combobox option:selected").text().split(' ');
                $('.table tr:last').after('<tr><td>' + $('.table tr').length + '</td><td>' + temp1[0] + '</td><td>' + temp1[1] + '</td></tr>');
            });
        });

        function removeItem() {
            $('.table tbody tr:first').remove();
            //.eq() -- You can also use this to fetch nth row
        }
    </script>
</head>
<body>
    <select class="combobox form-control">
        <option value="" selected="selected">Point Guard</option>
        <option value="CP3">Chris Paul (93)</option>
    </select>
    <button onclick="removeItem()">Remove First Row</button>
    <table class="table">
        <thead>
            <tr>
                <th>Position</th>
                <th>First Name</th>
                <th>Last Name</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>Mark</td>
                <td>Otto</td>
            </tr>
            <tr>
                <td>2</td>
                <td>Jacob</td>
                <td>Thornton</td>
            </tr>
            <tr>
                <td>3</td>
                <td>Larry</td>
                <td>the Bird</td>
            </tr>
        </tbody>
    </table>


</body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM