替换textarea框内的文本

时间:2012-02-08 18:30:58

标签: javascript

我有以下内容:

<textarea name="comment"><p>Good job.</p></textarea>

使用JavaScript,我想将“好工作”替换为“以下是我对作业进行评分的方式:”。

我对字符串更换感到不舒服。

2 个答案:

答案 0 :(得分:4)

您的用户个人资料上有jquery。所以这是一个使用它的答案:

$('textarea[name="comment"]').text("<p>Here's how I graded your assignment:</p>");

我建议在textarea中添加一个类并通过类选择它。上面的代码假设您没有在页面上使用名称“comment”的另一个textarea。

这会更好:

<textarea name="comment" class="some-better-name-here"><p>Good job.</p></textarea>
$('textarea.some-better-name-here').text("<p>Here's how I graded your assignment:</p>");

这里有效: http://jsfiddle.net/MCVbg/

答案 1 :(得分:1)

纯粹的Javascript解决方案:

var myTextArea = document.getElementsByName("comment")[0];
myTextArea.value = myTextArea.value.replace("Good job", "Here's how I graded your assignment:");

最好提供textarea和ID,然后使用getElementById选择它。