How to modify pasted data ? Jquery

别等时光非礼了梦想. 提交于 2019-12-10 10:18:19

问题


I followed this question JavaScript get clipboard data on paste event (Cross browser) to get the pasted data from the clipboard, but I used jquery instead. Now that I got the data, I removed all html tag. But I don't know how to paste it. element is a contenteditable div

element.on('paste', function (e) {
  var clipboardData, pastedData;
  e.preventDefault();
  // Get pasted data via clipboard API
  clipboardData = e.clipboardData || window.clipboardData || e.originalEvent.clipboardData;
  pastedData = clipboardData.getData('Text').replace(/<[^>]*>/g, "");
  // How to paste pasteddata now?
  console.log(pastedData);
});

回答1:


Might be easier to let the paste proceed and update element immediately after. Would depend on use case also as cursor position could be lost this way

$(':input').on('paste', function (e) {
    var $el = $(this); 
    setTimeout(function () {
        $el.val(function(){
            return this.value.replace(/foo/g, "bar"); 
        })
    });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>foo was here</p>
<textarea></textarea>



回答2:


I found the answer and I am gonna share it. In order to sanitize the clipboard from html tags, you should paste this:

             element.on('paste', function (e) {
                    e.preventDefault();
                    var text;
                    var clp = (e.originalEvent || e).clipboardData;
                    if (clp === undefined || clp === null) {
                        text = window.clipboardData.getData("text") || "";
                        if (text !== "") {
                            text = text.replace(/<[^>]*>/g, "");
                            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 !== "") {
                            text = text.replace(/<[^>]*>/g, "");
                            document.execCommand('insertText', false, text);
                        }
                    }
                });

Credit: l2aelba




回答3:


Well, it depends on what element are you going to paste in. You could use jQuery or native Javascript to achieve!

Maybe like $(targetNode).append(pastedData) or document.getElementById('targetNode').innerText = pastedData



来源:https://stackoverflow.com/questions/43438665/how-to-modify-pasted-data-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!