将文本追加到之后特定行的文本区域

append text to textarea on specific line after

本文关键字:文本 区域 之后 追加      更新时间:2023-09-26

假设我想将文本附加到特定动态行上的textarea。例如,我有一个checkboxes列表,它们的id范围从0-i。现在我还有一个textarea,其行数与id范围完全相同。因此,如果用户单击复选框 id 2 ,我希望textarea中的第三行附加一些文本。

您是否必须像这样先拆分textarea

var todolines = $('#todoListSave').val().split(''n');然后单独附加文本,还是有更好的方法?

你可以

做类似的事情

var $text = $('textarea');
//to initiate the value not required if the textarea value is already given
$text.val(new Array($(':checkbox').length + 1).join(''n'));
$(':checkbox').change(function() {
  var split = $text.val().split(''n');
  if (this.checked) {
    split[this.id] += this.value;
  } else {
    var regex = new RegExp(RegExp.escape(this.value) + '$');
    split[this.id] = split[this.id].replace(regex, '')
  }
  $text.val(split.join(''n'));
})
if (!RegExp.escape) {
  RegExp.escape = function(value) {
    return value.replace(/['-'[']{}()*+?.,'''^$|#'s]/g, "''$&")
  };
}
textarea {
  min-height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" id="0" value="1" />
<input type="checkbox" id="1" value="2" />
<input type="checkbox" id="2" value="3" />
<input type="checkbox" id="3" value="4" />
<input type="checkbox" id="4" value="5" />
<textarea></textarea>