如何在textarea元素顶部添加文本?(jQuery实现)
解决textarea前置添加文本的问题
你当前用的$('#textarea_id').append("New text added");是把内容追加到textarea末尾,要实现顶部添加,需要把新文本和原有内容拼接后重新赋值给textarea,具体可以这样做:
基础实现
直接获取textarea现有内容,将新文本放在前面,再设置回去:
$('#textarea_id').val("New text added" + $('#textarea_id').val());
如果需要新文本和原有内容换行分隔,加上\n即可:
$('#textarea_id').val("New text added\n" + $('#textarea_id').val());
封装复用(可选)
如果需要多次调用,可以封装成函数:
function prependToTextarea(textareaSelector, newContent) { const $textarea = $(textareaSelector); $textarea.val(newContent + $textarea.val()); } // 点击按钮时调用示例 $('button').click(function() { prependToTextarea('#textarea_id', "New text added\n"); });
原理说明:textarea的内容是通过val()方法管理的,不像普通DOM元素可以直接用prepend(),所以需要通过拼接字符串的方式实现前置添加。
内容的提问来源于stack exchange,提问作者Eduardo
相关产品推荐
相关产品推荐

