将文本插入光标所在的文本区域(不追加到末尾)



所以,我有一个文本区域,我想通过单击按钮将文本添加到其中。

但是,当我这样做时,它会附加到框的末尾而不是我的光标所在的位置。我怎样才能做到这一点?

JS小提琴在这里:https://jsfiddle.net/ukLaz8cm/127/

$(document).ready(function() {
  $("#emojionearea1").emojioneArea({
    pickerPosition: "right",
    tonesStyle: "bullet",
    events: {
      keyup: function(editor, event) {
        console.log(editor.html());
        console.log(this.getText());
      }
    }
  });
});
$('.aClass').click(function(e) {
  e.preventDefault(); //to prevent the default behaviour of a tag 
  var val = $('#emojionearea1').data("emojioneArea").getText(); //get prvious value
  if ($(this).text() == 'Test 1') {
    $('#emojionearea1').data("emojioneArea").setText(val + "rn" + 'Thank You');
  } else {
    $('#emojionearea1').data("emojioneArea").setText(val + "rn" + 'Good Luck');
  }
});
* {
  font-family: Arial, Helvetica, san-serif;
}
.row:after,
.row:before {
  content: " ";
  display: table;
  clear: both;
}
.span6 {
  float: left;
  width: 48%;
  padding: 1%;
}
.emojionearea-standalone {
  float: right;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//rawgit.com/mervick/emojionearea/master/dist/emojionearea.js"></script>
<link href="https://rawgit.com/mervick/emojionearea/master/dist/emojionearea.min.css" rel="stylesheet" type="text/css" />  
<a href="#" class="aClass" data-text="Thank You">Test 1</a> Clicking this will add "Thank you" to textarea<br/>
<a href="#" class="aClass" data-text="Good Luck">Test 2</a> Clicking this will add "Good luck" to textarea<br/>
<div class="row">
  <div class="span6">
    <textarea id="emojionearea1"></textarea>
  </div>
</div>

您正在设置整个文本区域的文本。

看看这个 在光标使用 Javascript/jquery 的地方插入文本

最新更新