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

后端 未结 12 660
失恋的感觉
失恋的感觉 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条回答
  •  Happy的楠姐
    2020-12-17 10:22

    There are alot of applicable answers here that would work for what you want. Here is what I would do in your circumstance. This allows for the changing of a text variable that you would most likely use, you can set it or the user can set it with another field, etc.

    codepen here

    the jist of it would be something like this.

    $(document).ready(function(){
      function deployText(){
        var textArray = [];
        var textToAdd = 'let\'s go ahead and add some more text';
        var textarea = $('textarea');
        var origValue = textarea.text();
        textArray.push(origValue);
    
        $('button').on('click', function(e){
          textArray.push(textToAdd);
          textarea.text(textArray);
          console.log(textArray.length);
          console.log(textArray);
        });
    
        $(document).on('keypress', function(e){
          var zKey = 26;
          if(e.ctrlKey && e.which === zKey){
            removePreviousText();
          }
        })
    
        function removePreviousText(){
          console.log(textArray);
          if(textArray.length > 1){
            textArray.pop();
            $('textarea').text(textArray);
          }
        }
      }
      deployText()
    })
    

提交回复
热议问题