如何在HTML5表中的当前行下创建一个空行?

时间:2015-05-21 06:54:37

标签: jquery html5

我正在尝试创建一个可编辑的表,在填充行之后,在按Tab键按钮后会在当前行下面呈现一个空行。最初在表加载时应出现一个空行。请有人帮我实现我的要求。

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Dynamic table</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js">        </script>
</head>
<body>
    <table class="table">
        <thead>
            <tr>
                <th>#</th>
                <th>user/site</th>
                <th>channel name</th>
                <th>actions</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td contentEditable="true">1</td>
                <td contentEditable="true">www.google.com</td>
                <td contentEditable="true">channel-1</td>
                <td contentEditable="true">delete</td>
            </tr>
            <tr>
                <td contentEditable="true">2</td>
                <td contentEditable="true">www.google.com</td>
                <td contentEditable="true">channel-1</td>
                <td contentEditable="true">delete</td>
            </tr>
            <!-- and so on -->
        </tbody>
    </table>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

只需在ready - 处理程序中定义javascript,即可在页面加载时追加新行。 要在最后tab点击td时添加新行,您需要收听tab-key(密码9,请参阅here以获取完整参考)。在动态添加元素时,您必须使用event-delegation

$(document).ready(function(){    
    $('.table tbody').append('<tr><td contenteditable="true"></td><td contenteditable="true"></td><td contenteditable="true"></td><td contenteditable="true"></td></tr>');

    $('.table').on('keydown', 'td:last-child', function (e) {
        var keyCode = e.keyCode || e.which;

        if (keyCode == 9) {
            $('tbody').append('<tr><td contenteditable="true"></td><td contenteditable="true"></td><td contenteditable="true"></td><td contenteditable="true"></td></tr>');
        }
    });
});

<强> Demo

<强>参考

.append()

:last-child

答案 1 :(得分:0)

use:最后一个选择器,用于查找tbody中的最后一个tr,然后像这样附加html

$('tbody >tr:last').after('<tr><td contenteditable="true">4</td><td contenteditable="true">a</td><td contenteditable="true">a</td><td contenteditable="true">a</td></tr>');