How can I “undo” the programmatic insertion of text into a textarea?

后端 未结 12 709
失恋的感觉
失恋的感觉 2020-12-17 09:27

I have a textarea and a button. Clicking the button causes text to be inserted into the textarea.

Is there a way to allow a user to press Ctrl/Cmd+z to undo the inse

12条回答
  •  遥遥无期
    2020-12-17 10:13

    You can do like this,

    HTML

    Jquery

    var oldText = [],ctrl=false;
       $(function(){
          $("input[name=Insert]").click(function(){
              var text = oldText.length+1;
              oldText.push(text);
              var textAreaText = $('textarea').val();
              textAreaText +=text;
              $('textarea').val(textAreaText);
              $("input[name=insertText]").val('');
         });
         $('textarea').keydown(function(e){
                if(e.which == 17){ ctrl = true;}
         });
         $('textarea').keyup(function(e){
             var c = e.which;
             if(c == 17){ ctrl = false;}
             if(ctrl==true && c==90 ){
                oldText.pop(); 
                var text = '';
                $.each(oldText,function(i,ele){
                   text += ele;
                });
                $('textarea').val(text);
            }
         })
      })
    

    You can also check and experiment with the fiddle.

提交回复
热议问题