简体   繁体   English

如何替换html textarea中当前选择的文本?

[英]How to replace the currently selected text inside an html textarea?

How do I edit the selected text of a textarea form element? 如何编辑textarea表单元素的选定文本?

EDIT: as in edit it in-place, replacing the orignal text. 编辑:与就地编辑一样,替换原始文本。

This works: 这有效:

 function replaceIt(txtarea, newtxt) { $(txtarea).val( $(txtarea).val().substring(0, txtarea.selectionStart)+ newtxt+ $(txtarea).val().substring(txtarea.selectionEnd) ); } $("button").on('click', function() { replaceIt($('textarea')[0], 'fun') }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea>Hello world.</textarea> <button>Replace with fun</button> 

I found this: 我找到了这个:

 function wrapText(elementID, openTag, closeTag) { var textArea = $('#' + elementID); var len = textArea.val().length; var start = textArea[0].selectionStart; var end = textArea[0].selectionEnd; var selectedText = textArea.val().substring(start, end); var replacement = openTag + selectedText + closeTag; textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len)); } $('button').on('click', function() { wrapText('test', '<b>', '</b>'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea id="test">This is a test</textarea> <button>Surround with &lt;b&gt; tag</button> 

But personaly its not working with content-editable divs. 但个人而言,它不适用于内容可编辑的div。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM