關於html table單元格粘貼或輸入值時,只取純文本的三種方法

========第一種方法==============

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" type="text/css" href="https://www.layuicdn.com/layui/css/layui.css"/>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<button id="add" class="layui-btn-danger layui-btn">添加</button>
<table contenteditable="plaintext-only" id="table" class="layui-table">
    <thead>
    <tr>
        <td>標題1</td>
        <td>標題2</td>
        <td>標題3</td>
    </tr>
    </thead>
    <tbody>

    </tbody>
</table>

</body>
<script>
    $(function () {
        $("#add").click(function () {
            $("#table tbody").append(`<tr>
            <td></td>
            <td></td>
            <td></td>
        </tr>`)
        })
    })
</script>
</html>

 

 

===========第二種方法=============

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" type="text/css" href="https://www.layuicdn.com/layui/css/layui.css"/>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<button id="add" class="layui-btn-danger layui-btn">添加</button>
<table id="table" class="layui-table">
    <thead>
    <tr>
        <td>標題1</td>
        <td>標題2</td>
        <td>標題3</td>
    </tr>
    </thead>
    <tbody>

    </tbody>
</table>

</body>
<script>
    $(function () {
        $("#add").click(function () {
            $("#table tbody").append('<tr><td contenteditable="true"></td><td contenteditable="true"></td><td contenteditable="true"></td></tr>')
            $("#table td").on('paste',function (e){
               var that = e
               setTimeout(function (){
                   that.currentTarget.innerHTML = that.currentTarget.innerHTML.replace( /<[^>]*>/g, "" );
               })
            })
        })
    })
</script>
</html>

 

 

=============第三種方法===============

<div class='page3-emjoy5' contenteditable=='true'></div>
 
$(".page3-emjoy5").on("paste", function (e) {
    textInit(e)
});
 
function textInit(e) {
    e.preventDefault();
    var text;
    var clp = (e.originalEvent || e).clipboardData;
    if (clp === undefined || clp === null) {
        text = window.clipboardData.getData("text") || "";
        if (text !== "") {
            if (window.getSelection) {
                var newNode = document.createElement("span");
                newNode.innerHTML = text;
                window.getSelection().getRangeAt(0).insertNode(newNode);
            } else {
                document.selection.createRange().pasteHTML(text);
            }
        }
    } else {
        text = clp.getData('text/plain') || "";
        if (text !== "") {
            document.execCommand('insertText', false, text);
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章