粘贴事件未按预期工作

Sex*_*ast 1 html javascript jquery

我正在尝试这个简单的代码。我想要的是,当paste在第二个输入文本框中触发事件时,在复制其内容、删除readonly前一个文本框的属性并将其粘贴到那里之后,应该清除该事件。然而,什么也没有发生。

paste事件被正常触发,因为如果我用简单的替换计时器中的代码alert,它就会起作用。谁能告诉我这里出了什么问题吗?

<!DOCTYPE html>
<html>
  <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
    </script>
    <script>
       $(document).ready(function(){
         $(".boo").bind("input paste",function() { 
         elem = this;
         setTimeout(function() { 
             $(".foo").removeAttr("readonly");
             $(".foo").text($(elem).text());
             $(elem).text("");  
         },100);
        });
      });
  </script>
</head>
 <body>
   <input class = 'foo' type = 'text' /><input class = 'boo' type = 'text' />
 </body>
</html>
Run Code Online (Sandbox Code Playgroud)

Onu*_*rım 5

首先,你应该使用输入控件.val()而不是with。.text()

$(document).ready(function () {

    $("input.boo").bind("paste", function () { //also changed the binding too
        var elem = $(this);
        setTimeout(function () {
            $(".foo").val(elem.val());
            elem.val("");
        }, 100);
    });

});
Run Code Online (Sandbox Code Playgroud)

此外,当文本粘贴到控件中时,您的绑定事件会被触发两次。这是因为,您已将inputpaste事件绑定到具有“boo”类的元素。

所以在这里,而不是:

$(".boo").bind("input paste", function() {});
Run Code Online (Sandbox Code Playgroud)

用这个:

$("input.boo").bind("paste", function() {});
Run Code Online (Sandbox Code Playgroud)

这将仅将paste事件绑定到具有“boo”类的输入元素。

请参阅更新的 jsFiddle 示例