使用 jQuery 在 textarea 中插入文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/946534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert text into textarea with jQuery
提问by Oliver Stubley
I'm wondering how I can insert text into a text area using jquery, upon the click of an anchor tag.
我想知道如何在单击锚标记时使用 jquery 将文本插入文本区域。
I don't want to replace text already in textarea, I want to append new text to textarea.
我不想替换 textarea 中已有的文本,我想将新文本附加到 textarea。
采纳答案by TStamper
From what you have in Jason's comments try:
从你在杰森的评论中得到的尝试:
$('a').click(function() //this will apply to all anchor tags
{
$('#area').val('foobar'); //this puts the textarea for the id labeled 'area'
})
Edit-To append to text look at below
编辑 -要附加到文本,请看下面
$('a').click(function() //this will apply to all anchor tags
{
$('#area').val($('#area').val()+'foobar');
})
回答by Aniebiet Udoh
I like the jQuery function extension. However, the thisrefers to the jQuery object not the DOM object. So I've modified it a little to make it even better (can update in multiple textboxes / textareas at once).
我喜欢 jQuery 函数扩展。但是,this指的是 jQuery 对象而不是 DOM 对象。所以我对其进行了一些修改以使其更好(可以一次在多个文本框/文本区域中更新)。
jQuery.fn.extend({
insertAtCaret: function(myValue){
return this.each(function(i) {
if (document.selection) {
//For browsers like Internet Explorer
this.focus();
var sel = document.selection.createRange();
sel.text = myValue;
this.focus();
}
else if (this.selectionStart || this.selectionStart == '0') {
//For browsers like Firefox and Webkit based
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length;
this.selectionEnd = startPos + myValue.length;
this.scrollTop = scrollTop;
} else {
this.value += myValue;
this.focus();
}
});
}
});
This works really well. You can insert into multiple places at once, like:
这真的很好用。您可以一次插入多个位置,例如:
$('#element1, #element2, #element3, .class-of-elements').insertAtCaret('text');
回答by Thinker
I use this function in my code:
我在我的代码中使用这个函数:
$.fn.extend({
insertAtCaret: function(myValue) {
this.each(function() {
if (document.selection) {
this.focus();
var sel = document.selection.createRange();
sel.text = myValue;
this.focus();
} else if (this.selectionStart || this.selectionStart == '0') {
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos) +
myValue + this.value.substring(endPos,this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length;
this.selectionEnd = startPos + myValue.length;
this.scrollTop = scrollTop;
} else {
this.value += myValue;
this.focus();
}
});
return this;
}
});
input{width:100px}
label{display:block;margin:10px 0}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Copy text from: <input id="in2copy" type="text" value="x"></label>
<label>Insert text in: <input id="in2ins" type="text" value="1,2,3" autofocus></label>
<button onclick="$('#in2ins').insertAtCaret($('#in2copy').val())">Insert</button>
It's not 100% mine, I googled it somewhere and then tuned for mine app.
这不是 100% 我的,我在某个地方用谷歌搜索了它,然后调整了我的应用程序。
Usage: $('#element').insertAtCaret('text');
用法: $('#element').insertAtCaret('text');
回答by Marcus
I know this is an old question but for people searching for this solution it's worth noting that you should not use append() to add content to a textarea. the append() method targets innerHTML not the value of the textarea. The content may appear in the textarea but it will not be added to the element's form value.
我知道这是一个老问题,但对于搜索此解决方案的人来说,值得注意的是,您不应使用 append() 将内容添加到 textarea。append() 方法针对的是innerHTML 而不是textarea 的值。内容可能会出现在 textarea 中,但不会添加到元素的表单值中。
As noted above using:
如上所述,使用:
$('#textarea').val($('#textarea').val()+'new content');
will work fine.
会正常工作。
回答by panchicore
this one allow you "inject" a piece of text to textbox, inject means: appends the text where cursor is.
这个允许你“注入”一段文本到文本框,注入意味着:将文本附加到光标所在的位置。
function inyectarTexto(elemento,valor){
var elemento_dom=document.getElementsByName(elemento)[0];
if(document.selection){
elemento_dom.focus();
sel=document.selection.createRange();
sel.text=valor;
return;
}if(elemento_dom.selectionStart||elemento_dom.selectionStart=="0"){
var t_start=elemento_dom.selectionStart;
var t_end=elemento_dom.selectionEnd;
var val_start=elemento_dom.value.substring(0,t_start);
var val_end=elemento_dom.value.substring(t_end,elemento_dom.value.length);
elemento_dom.value=val_start+valor+val_end;
}else{
elemento_dom.value+=valor;
}
}
And you can use it like this:
你可以像这样使用它:
<a href="javascript:void(0);" onclick="inyectarTexto('nametField','hello world');" >Say hello world to text</a>
Funny and have more sence when we have "Insert Tag into Text" functionality.
当我们有“将标签插入文本”功能时,会更有趣并且更有意义。
works in all browsers.
适用于所有浏览器。
回答by Babak Bandpay
Hej this is a modified version which works OK in FF @least for me and inserts at the carets position
Hej 这是一个修改后的版本,它在 FF @least 中对我来说工作正常,并在插入符号位置插入
$.fn.extend({
insertAtCaret: function(myValue){
var obj;
if( typeof this[0].name !='undefined' ) obj = this[0];
else obj = this;
if ($.browser.msie) {
obj.focus();
sel = document.selection.createRange();
sel.text = myValue;
obj.focus();
}
else if ($.browser.mozilla || $.browser.webkit) {
var startPos = obj.selectionStart;
var endPos = obj.selectionEnd;
var scrollTop = obj.scrollTop;
obj.value = obj.value.substring(0, startPos)+myValue+obj.value.substring(endPos,obj.value.length);
obj.focus();
obj.selectionStart = startPos + myValue.length;
obj.selectionEnd = startPos + myValue.length;
obj.scrollTop = scrollTop;
} else {
obj.value += myValue;
obj.focus();
}
}
})
回答by Jason
have you tried:
你有没有尝试过:
$("#yourAnchor").click(function () {
$("#yourTextarea").val("your text");
});
not sure about autohighlighting, though.
不过,不确定自动突出显示。
EDIT:
编辑:
To append:
附加:
$("#yourAnchor").click(function () {
$("#yourTextarea").append("your text to append");
});
回答by Russ Cam
What you ask for should be reasonably straightforward in jQuery-
您在jQuery中要求的内容应该相当简单-
$(function() {
$('#myAnchorId').click(function() {
var areaValue = $('#area').val();
$('#area').val(areaValue + 'Whatever you want to enter');
});
});
The best way that I can think of highlighting inserted text is by wrapping it in a span with a CSS class with background-color
set to the color of your choice. On the next insert, you could remove the class from any existing spans (or strip the spans out).
我能想到的突出显示插入文本的最佳方法是将它包装在一个带有 CSS 类的跨度中,并background-color
设置为您选择的颜色。在下一次插入时,您可以从任何现有跨度中删除该类(或去除跨度)。
However, There are plenty of free WYSIWYG HTML/Rich Text editors available on the market, I'm sure one will fit your needs
但是,市场上有很多免费的 WYSIWYG HTML/Rich Text 编辑器,我相信其中一款会满足您的需求
- TinyMCE- JavaScript WYSIWYG editor
- Rich Text Editor- YUI Library
- 10 jQuery and Non-jQuery JavaScript Rich Text Editors
- TinyMCE- JavaScript 所见即所得编辑器
- 富文本编辑器- YUI 库
- 10 个 jQuery 和非 jQuery JavaScript 富文本编辑器
回答by Avram Cosmin
Here is a quick solution that works in jQuery 1.9+:
这是一个适用于 jQuery 1.9+ 的快速解决方案:
a) Get caret position:
a) 获取插入位置:
function getCaret(el) {
if (el.prop("selectionStart")) {
return el.prop("selectionStart");
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
};
b) Append text at caret position:
b) 在插入符号位置附加文本:
function appendAtCaret($target, caret, $value) {
var value = $target.val();
if (caret != value.length) {
var startPos = $target.prop("selectionStart");
var scrollTop = $target.scrollTop;
$target.val(value.substring(0, caret) + ' ' + $value + ' ' + value.substring(caret, value.length));
$target.prop("selectionStart", startPos + $value.length);
$target.prop("selectionEnd", startPos + $value.length);
$target.scrollTop = scrollTop;
} else if (caret == 0)
{
$target.val($value + ' ' + value);
} else {
$target.val(value + ' ' + $value);
}
};
c) Example
c) 示例
$('textarea').each(function() {
var $this = $(this);
$this.click(function() {
//get caret position
var caret = getCaret($this);
//append some text
appendAtCaret($this, caret, 'Some text');
});
});
回答by Long
It works good for me in Chrome 20.0.11
它在 Chrome 20.0.11 中对我很有用
var startPos = this[0].selectionStart;
var endPos = this[0].selectionEnd;
var scrollTop = this.scrollTop;
this[0].value = this[0].value.substring(0, startPos) + myVal + this[0].value.substring(endPos, this[0].value.length);
this.focus();
this.selectionStart = startPos + myVal.length;
this.selectionEnd = startPos + myVal.length;
this.scrollTop = scrollTop;