[英]Preserve tabs when reading from a textarea after adding via JavaScript
I'm having a problem with preserving tab characters when reading the value of a textarea. 读取textarea的值时,我在保留制表符时遇到问题。 I'm adding the tabs as follows:
我添加的标签如下:
$("#code-editor").keydown(function (e) {
if (e.keyCode === 9) { // tab was pressed
// get caret position/selection
var start = this.selectionStart;
var end = this.selectionEnd;
var $this = $(this);
var value = $this.val();
// set textarea value to: text before caret + tab + text after caret
$this.val(value.substring(0, start)
+ "\t"
+ value.substring(end));
// put caret at right position again (add one for the tab)
this.selectionStart = this.selectionEnd = start + 1;
// prevent the focus lose
e.preventDefault();
}
});
The tabs are inserted correctly and are displayed in the textarea as expected. 选项卡已正确插入,并按预期显示在文本区域中。 The problem occurs when I then read the value of the textrea and try to replace to tab characters with html formatting.
当我然后读取textrea的值并尝试用html格式替换为制表符时,就会出现问题。
$("#code-editor").keyup(function (e) {
var value = $(this).val();
//Do formatting
var lines = value.split("\n");
var newvalue = "";
for (var i = 0; i < lines.length; i++) {
lines[i].replace(/\t/g, "<span style='padding-left:3em'></span>");
lines[i] += "<br />";
newvalue += lines[i];
}
$('#editor-displayarea').html(newvalue);
});
I have discovered that the tabs do not seem to be preserved when reading from textarea. 我发现从textarea读取时似乎未保留这些选项卡。
Is there a way around this or have I taken the wrong approach? 有没有解决的办法,或者我采取了错误的方法?
Thanks. 谢谢。
Update: I have tried using a few variations on the regular expression as stated in the comment below but to no avail. 更新:我尝试对正则表达式使用一些变体,如下面的评论所述,但无济于事。
You are not storing the value when you replace the tabs. 替换选项卡时,您没有存储值。 Try something like this (I would leave the
in the span as well): 尝试这样的操作(我也会把
留在范围内):
for (var i = 0; i < lines.length; i++) {
var replaced = lines[i].replace(/\t/g, "<span style='padding-left:3em'> </span>");
replaced += "<br />";
newvalue += replaced;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.