jQuery jquery如何获取粘贴的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9494283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:53:41  来源:igfitidea点击:

jquery how to get the pasted content

jquerypaste

提问by greenbandit

I have a little trouble catching a pasted text into my input:

我在将粘贴的文本捕获到我的输入中时遇到了一些麻烦:

 <input type="text" id="myid" val="default">
 $('#myid').on('paste',function(){
        console.log($('#myid').val());
 });  

console.log shows:

console.log 显示:

default

How I catchthe pasted text and get ready to use?

我如何catch粘贴文本并准备使用?

回答by cateyes

The accepted answer is actually hacky and ugly, seems to be suggested quite often for the paste event on stackoverflow. I think a better way to do it is this

接受的答案实际上是hacky和丑陋的,似乎经常被建议用于stackoverflow上的粘贴事件。我认为更好的方法是这样

$('#someInput').bind('paste', function(e) {
    var data = e.originalEvent.clipboardData.getData('Text');
    //IE9 Equivalent ==> window.clipboardData.getData("Text");   
});

回答by adeneo

Because the pasteevent is triggered before the inputs value is updated, the solution is to either:

由于paste事件是在输入值更新之前触发的,因此解决方案是:

  1. Capture the data from the clipboard instead, as the clipboards data will surely be the same as the data being pasted into the input at that exact moment.

  2. Wait until the value hasupdated using a timer

  1. 相反,从剪贴板中捕获数据,因为剪贴板数据肯定与当时粘贴到输入中的数据相同。

  2. 等到值使用定时器更新

Luckily, years after the original answer was posted, most modern browsers now support the fantastic Clipboard API, a much more elegant solution to capturing data from the clipboard.

幸运的是,在原始答案发布多年后,大多数现代浏览器现在都支持出色的Clipboard API,这是一种从剪贴板捕获数据的更优雅的解决方案。

For browsers that don't support the Clipboard API, we could fall back to the unreliable event.clipboardDataif we do some checking as to which version, if any, is supported in the browser.

对于不支持 Clipboard API 的浏览器,event.clipboardData如果我们对浏览器支持哪个版本(如果有)进行一些检查,我们可能会退回到不可靠的版本。

As a final fallback, using a timer to delay until the inputs value is updated, will work in all browsers, making this a truly cross-browser solution.

作为最后的回退,使用计时器延迟直到输入值更新,将适用于所有浏览器,使其成为真正的跨浏览器解决方案。

I've made a convenient function that handles everything

我做了一个方便的函数来处理一切

function catchPaste(evt, elem, callback) {
  if (navigator.clipboard && navigator.clipboard.readText) {
    // modern approach with Clipboard API
    navigator.clipboard.readText().then(callback);
  } else if (evt.originalEvent && evt.originalEvent.clipboardData) {
    // OriginalEvent is a property from jQuery, normalizing the event object
    callback(evt.originalEvent.clipboardData.getData('text'));
  } else if (evt.clipboardData) {
    // used in some browsers for clipboardData
    callback(evt.clipboardData.getData('text/plain'));
  } else if (window.clipboardData) {
    // Older clipboardData version for Internet Explorer only
    callback(window.clipboardData.getData('Text'));
  } else {
    // Last resort fallback, using a timer
    setTimeout(function() {
      callback(elem.value)
    }, 100);
  }
}

// to be used as 

$('#myid').on('paste', function(evt) {
  catchPaste(evt, this, function(clipData) {
    console.log(clipData);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="myid" />

Note that getting the data from the clipboard only gets you the pasted text, while waiting for the inputs value to update is the only solution above that actually gets the entire value of the input, including the newly pasted text.

请注意,从剪贴板获取数据只会让您获得粘贴的文本,而等待输入值更新是上述唯一实际获取整个输入值(包括新粘贴的文本)的解决方案。

回答by Danial

using "input" avoids the Timeout kludge on paste and is better than change which can not work for things like paste or search events.

使用“输入”避免了粘贴时的超时混乱,并且比不能用于粘贴或搜索事件之类的更改要好。

$('input').on('input', function(e) {
    var type = e.originalEvent.inputType;
    if (typeof(type) == 'undefined'){
       type = 'search';
    switch(type){
    case 'search':
    case 'deleteByCut':
    case 'insertText':
    case 'insertFromPaste':
    case 'deleteContentBackward':
       var content = $(this).val();
    }
});

Search is a special case which doesnt generate an input type; it's basically the same as 'deleteByCut' in function in that it clears the field.

搜索是一种特殊情况,它不会生成输入类型;它在功能上与 'deleteByCut' 基本相同,因为它清除字段。

You could, of course, have different handlers for each case if necessary.

当然,如有必要,您可以为每种情况使用不同的处理程序。

回答by Murat Kezli

$('#myid').on('paste' , function(e){
   get_content(this);
});

function get_content(gelen){
var value_input = $(gelen).val();
document.getElementById("write-value").innerHTML = value_input;
console.log(value_input);
}
input{ width: calc(100% - 16px); padding:8px; font-size:large}
div{ color:red; margin-top:16px; padding:8px; font-size:large}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="myid" onkeyUP="get_content(this)" >

<div id="write-value">
</div>

回答by mike

JSfiddle EXAMPLE here

JSfiddle 示例在这里

Bigger picture, I think you usually want three events:

更大的图景,我认为您通常需要三个事件:

  1. When the user pastes
  2. When the user hits <enter>
  3. When the textbox looses focus.
  1. 当用户粘贴
  2. 当用户点击 <enter>
  3. 当文本框失去焦点时。

I DON'T want on('input')because that raises an event for every keypress.

我不想要,on('input')因为每次按键都会引发一个事件。

This way, you get one event, when the user gets donemaking input to the text box.

这样,当用户完成对文本框的输入,您会得到一个事件。

$(document).ready(function () {

            $('#myid').keydown(function (e) {
                var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
                if (key == 13) {
                    e.preventDefault();
                    alert($(this).val());
                }
            }).on("change", function () {
                alert($(this).val());
            }).on("paste", function (e) {
                var _this = this;
                // Short pause to wait for paste to complete
                setTimeout(function () {
                    alert($(_this).val());
                }, 100);
            });
        });

回答by Miguel

Try this or adding a timeOut too:

试试这个或添加超时:

   $('#myid').on('paste',function(){
           console.log(this.value);
    });