Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - Way to make backspace delete whole words at a time

I have a text area:

<textarea type="input"  id="txtText">Hello+world-how*are+you</textarea>

I want a way for backspace to delete a whole word every time it is clicked using Javascript or Angular js. When I press backspace I want it to split by operators and delete from the end. The first backspaces in the above example would delete 'you' then 'are' then 'how' and so on. But if the mouse is on 'world' then it deletes 'world' first, then 'Hello'.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a solution than uses the data attribute to match for changes: jsFiddle

jQuery('#EditableDiv').keyup(function(e) {
  if (jQuery(e.target).text().length < jQuery(e.target).attr("data-value").length) {
    var data = jQuery(e.target).attr("data-value").split(" ");
    var text = jQuery(e.target).text().split(" ");
    for (var a = 0; a < data.length; a++) {
      if (text[a] != data[a]) {
        text.splice(a, 1);
        break;
      }
    }
    jQuery(e.target).text(text.join(" "));
  }
  jQuery(e.target).attr("data-value", jQuery(e.target).text());

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="EditableDiv" contenteditable="true" data-value="Hello, how are you" class="size">Hello, how are you</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...