replace linebreaks to get them working with jquery

若如初见. 提交于 2020-01-04 03:44:07

问题


I have following small script to preview some text before submitting it to store in a database:

jQuery(function($) {
    var input = $('#contents'),
    preview = $('#previewaccordion div.viewcontents');

    input.keyup(function(e) {
        preview.html(input.val());
    });
});

but if I type text with line-breaks it ignores them and writes all of them in one line. How could I replace the line-breaks so that they show correctly?


回答1:


I assume that you are using a textarea for the input. There are \n used as linebreaks, which have no influence in HTML. So you have to replace them with br-tags:

input.val().replace(/\n/g, "<br />");



回答2:


It's nothing to do with jQuery: Linebreaks in HTML are not significant, they're just whitespace (like spaces and tabs).

To force a linebreak in HTML, you use a <br> tag. So you could change

preview.html(input.val());

to

preview.html(input.val().replace(/\r?\n/g, '<br>'));

Note that you're also not escaping HTML special characters (like < or &), and so if you type them, your output may not be correct. So you might go with:

preview.html(input.val().replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\r?\n/g, '<br>'));

And finally, I'd hook keypress as well as keyup, so you see characters created via key repeat (which fires keypress, but not keyup).

Live example | source




回答3:


Hiya demo here: http://jsfiddle.net/STnhV/1/

hope this helps! cheers!

Jquery Code:

$(document).ready(function() {
    $('#inputfoo').keyup(function() {
       $('#outputbar').html($(this).val().replace(/\n/g,'<br/>')); 
    });
});

​



回答4:


Replace the linebreaks to html break tags when you render the output from the database.



来源:https://stackoverflow.com/questions/9963158/replace-linebreaks-to-get-them-working-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!