我试了一下(jsfiddle),但它没有用。
如何看到警报为空。它就像.val()函数在复制字符串之前就开始了。
$(document).on('paste', '#pasteIt', function(){
alert($("#pasteIt").val());
var withoutSpaces = $("#pasteIt").val();
withoutSpaces = withoutSpaces.replace(/\s+/g, '');
$("#pasteIt").text(withoutSpaces);
});
为什么?
答案 0 :(得分:8)
获取剪贴板数据
$(document).on('paste', '#pasteIt', function(e) {
e.preventDefault();
// prevent copying action
alert(e.originalEvent.clipboardData.getData('Text'));
var withoutSpaces = e.originalEvent.clipboardData.getData('Text');
withoutSpaces = withoutSpaces.replace(/\s+/g, '');
$(this).val(withoutSpaces);
// you need to use val() not text()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="pasteIt" placeholder="Paste something here">
参考:https://forum.jquery.com/topic/paste-event-get-the-value-of-the-paste#14737000004101955
答案 1 :(得分:2)
使用setTimeout
,这会延迟检查,以便检索值。
请查看here。
$(document).on('paste', '#pasteIt', function () {
setTimeout(function () {
alert($("#pasteIt").val());
var withoutSpaces = $("#pasteIt").val();
withoutSpaces = withoutSpaces.replace(/\s+/g, '');
$("#pasteIt").val(withoutSpaces);
}, 1);
});
答案 2 :(得分:0)
所以,你想要这个:
$(document).on('paste', '#pasteIt', function(e) {
window.setTimeout(function() {
var withoutSpaces = $("#pasteIt").val();
withoutSpaces = withoutSpaces.replace(/\s+/g, '');
$("#pasteIt").val(withoutSpaces);
}, 1);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>
<span>Enter: </span>
<input id="pasteIt">
</html>
&#13;