如何在jquery中选择文本之前和之后进行选择

时间:2015-10-30 11:01:35

标签: jquery text input

我想在文本框中选择文本之前和之后找到文本

例如

<input id="selectionBox" />

实施例: selectionBox输入值等于“检查输入的地址......”

用户在“检查添加”之后和之前选择“r”进行“ess for typing ...”之前我想在“r”之前和之后存储单独的变量

$('#selectionBox').select(function(e) { 
    var start = e.target.selectionStart;
    var end = e.target.selectionEnd;
    var selectedtext  = $('#selectionBox').val().substring(start, end);
    // find before and after selected text  
    //var beforeSel = before selection;
    //var afterSel = after selection;
})

编辑1: 我希望在文本之前和之后找到更改selctionBox值,就像这样

var textboxValue = beforeSel + "<blank>" + selectedtext  + "<blank>" + afterSel;
$("#selectionBox").val(textboxValue);

怎么办?谢谢

1 个答案:

答案 0 :(得分:0)

您只需使用与获取所选文本相同的技术。

使用substring(0, start)获取选择前的文字,并substring(end)获取选择后的文字。

&#13;
&#13;
$('#selectionBox').select(function(e) {
  var start = e.target.selectionStart;
  var end = e.target.selectionEnd;
  var text = $('#selectionBox').val();
  
  var selectedtext = text.substring(start, end);
  
  // find before and after selected text
  var beforeSel = text.substring(0, start);
  var afterSel = text.substring(end);

  $('#selected-text').text(selectedtext);
  $('#before-selection').text(beforeSel);
  $('#after-selection').text(afterSel);
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="selectionBox" />
<div>Selected Text: <span id="selected-text" style="color:blue"></span>
</div>
<div>Before Selection: <span id="before-selection" style="color:blue"></span>
</div>
<div>After Selection: <span id="after-selection" style="color:blue"></span>
</div>
&#13;
&#13;
&#13;