[英]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.