[英]Copy/Paste String in HTML Fields
我正在嘗試在新行的基礎上將一個字符串從記事本復制到 HTML 表格,但它對我不起作用,下面是您的幫助的代碼片段。 第一行應填充在字段 1 中,第二行應填充在字段 2 中,第三行應填充在字段 3 中
$("input[name=query]").on("paste", function() { var $this = $(this); setTimeout(function() { var id = $this.attr("id"), no = parseInt(id.substr(5)), //groups = $this.val().split(/\s+/); //groups = $this.val().split('.'); groups = $this.val().split(/[\n\r]/g); if (groups) { var i = 0; while (no <= 3 && i < groups.length) { $("#input" + no).val(groups[i]); ++no; ++i; } } }, 0); });
form { width: 500px; margin: 50px auto 0; } form h2 { text-align: center; text-decoration: underline; } form table { width: 100%; } form input { width: 100%; height: 40px; border-radius: 5px; outline: none; padding: 0 15px; border: 1px solid #000000; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <form name="form1" action="#" method="get" target=""> <h2>Copy/Paste String</h2> <table cellpadding="0" cellspacing="20"> <tr> <td width="100px"><h3>Line 1:</h3></td> <td><input id="input1" name="query" placeholder="Line 1" type="text"></td> </tr> <tr> <td width="100px"><h3>Line 2:</h3></td> <td><input id="input2" name="query" placeholder="Line 2" type="text" ></td> </tr> <tr> <td width="100px"><h3>Line 3:</h3></td> <td><input id="input3" name="query" placeholder="Line 3" type="text"></td> </tr> </table> </form>
下面是我試圖從記事本復制的 3 行行為是新行
This is Line 1
This is Line 2
This is Line 3
請查看我做錯的片段和指南
問題是當您粘貼到(單行)輸入時,您的換行符會丟失; 只有 textareas 會保留換行符; 普通輸入會將多行文本折疊成一行。
解決方案是不是從輸入而是通過事件的clipboardData()
區域讀取粘貼的輸入 - 不是人為的 jQuery 事件,而是原始(本機)事件。 jQuery 通過originalEvent
屬性公開這一點。
這也意味着您可以避免超時黑客攻擊。 總而言之:
let fields = $('input[name=query]');
$(document).on('paste', 'input[name=query]', evt => {
evt.preventDefault();
let pasted = evt.originalEvent.clipboardData.getData('text/plain');
pasted.split(/\n/).forEach((line, i) => fields[i].value = line);
});
(進一步閱讀:我關於破解傳入剪貼板數據的博客文章。)
你可以試試這個:
$("input[name=query]").on("paste", function(e) {
// Stop data actually being pasted into div
e.stopPropagation();
e.preventDefault();
// Get pasted data via clipboard API
pastedData = window.event.clipboardData.getData('Text');
// Do whatever with pasteddata
var $this = $(this);
setTimeout(function() {
var id = $this.attr("id"), no = parseInt(id.substr(5)),groups = pastedData.split("\n");
if (groups) {
var i = 0;
while (no <= 3 && i < groups.length) {
$("#input" + no).val(groups[i]);
++no;
++i;
}
}
}, 0);
});
祝你好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.