簡體   English   中英

如何修改粘貼數據? jQuery的

[英]How to modify pasted data ? Jquery

我按照這個問題JavaScript獲取粘貼事件(Cross瀏覽器)上的剪貼板數據,以從剪貼板中獲取粘貼的數據,但我使用了jquery。 現在我得到了數據,我刪除了所有的html標簽。 但我不知道如何粘貼它。 element是一個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);
});

可能更容易讓粘貼繼續並在之后立即更新元素。 將取決於用例,因為光標位置可能會以這種方式丟失

 $(':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> 

我找到了答案,我將分享它。 為了從html標簽清理剪貼板,你應該粘貼這個:

             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);
                        }
                    }
                });

圖片來源: l2aelba

好吧,這取決於你要粘貼的元素。你可以使用jQuery或本機Javascript來實現!

也許像$(targetNode).append(pastedData)document.getElementById('targetNode').innerText = pastedData

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM