.replace()只是临时的,javascript

时间:2014-06-26 09:30:46

标签: jquery forms

我正在创建一个论坛页面,并立即形成评论部分。因为当你按回车键时,它会在文本区域中输入\ n,这样的文本结果如下:
A
A
A
结束如A A A'。 我将此文本提交到数据库,因此我必须在提交之前执行此功能。所以我在表单上使用了onsubmit并将其指向以下函数:

 function ClearText() {
    $('#CommentBox').val().replace(/\n/g,'<br>');
    console.log($('#CommentBox').val());

当我在控制台上手动执行此操作时,我发现它实际上将换行标记转换为br标记。但是,当我运行此代码时,$(&#39;#CommentBox&#39;)。val()根本没有变化。 是否有其他方式在提交之前调用函数?或者有没有办法使这个.replace()更改成为永久性的?提前谢谢!

3 个答案:

答案 0 :(得分:2)

现在你只得到了值,你应该设置值,

 function ClearText() {
     $('#CommentBox').val($('#CommentBox').val().replace(/\n/g, '<br>'));
     console.log($('#CommentBox').val());
 }

答案 1 :(得分:1)

.replace()不会替换实际值,但会返回指定字符的替换值。您需要将其存储在变量中,然后再次设置

function ClearText() {
     var replaceVal = $('#CommentBox').val().replace(/\n/g,'<br>');
   $('#CommentBox').val(replaceVal )
    console.log($('#CommentBox').val());
}

答案 2 :(得分:0)

试试这个

function ClearText() {
       $('#CommentBox').val($('#CommentBox').val().replace(/\n/g,'<br>'))
       console.log($('#CommentBox').val());
    }