如何使用输入复制和粘贴excel列到HTML表?

时间:2017-10-25 21:01:34

标签: javascript jquery html

我想将excel列或任何类似的列表复制并粘贴到HTML表格中。我找到了这段代码,但是有一个问题。它像行一样粘贴数据。那么如何将其更改为像列一样粘贴?提前谢谢。



$(document).ready(function() {
        $('td input').bind('paste', null, function (e) {
            $this = $(this);
            setTimeout(function () {
                var columns = $this.val().split(/\s+/);
                var i;
                var input = $this;
                for (i = 0; i < columns.length; i++) {
                    input.val(columns[i]);
                    if( i % 3 !== 2){
                        input = input.parent().next().find('input');
                        } else{
                            input = input.parent().parent().next().find('input');
                        }
                    }
            }, 0);
        });
    } );
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
        </thead>
        <tbody>
            <tr>
                <td><input type="text"></td>
                <td><input type="text"></td>
                <td><input type="text"></td>
            </tr>
            <tr>
                <td><input type="text"></td>
                <td><input type="text"></td>
                <td><input type="text"></td>
            </tr>
            <tr>
                <td><input type="text"></td>
                <td><input type="text"></td>
                <td><input type="text"></td>
            </tr>
        </tbody>
    </table>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

以下是您的解决方案:

$(document).ready(function() {
        $('td input').bind('paste', null, function(e) {
            $input = $(this);
            setTimeout(function() {
                var values = $input.val().split(/\s+/),
                    row = $input.closest('tr'),
                    col = $input.closest('td').index();
                    console.log(col);
                for (var i = 0; i < values.length; i++) {
                    row.find('input').eq(col).val(values[i]);
                    row = row.next();
                }
            }, 0);
        });
    });