nl2br()等效于javascript [英] nl2br() equivalent in javascript

查看:97
本文介绍了nl2br()等效于javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

jQuery将换行符转换为br(nl2br等价物)

目前我为每个 evt.which == 13 添加< BR> 。 JavaScript是否有 nl2br(),所以我可以取消这个 evt.which == 13

Currently I add <BR> for each evt.which == 13. Is there a nl2br() for JavaScript, so I can do away with this evt.which == 13?

这与php.js的不同之处

$('#TextArea').keypress(function(evt) {

    if (evt.which == 13) {

        var range           = $('#TextArea').getSelection();
        var image_selection = range.text;

        $('#TextArea').replaceSelection('<BR>');
        $('#TextArea1').html($('#TextArea').val());
    }
});


推荐答案

看看在php.js上的nl2br 这看起来正是你正在寻找的。基本上,它是:

Take a look at nl2br on php.js which seems exactly what you're looking for. Basically, it's:

function nl2br (str, is_xhtml) {
    if (typeof str === 'undefined' || str === null) {
        return '';
    }
    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}

编辑:

使用 nl2br()的示例可能会更改为:


your example using nl2br() may be changed like this:

$('#TextArea').keypress(function(evt){
        $('#TextArea1').html(nl2br($('#TextArea').val()));
    });

(请注意,此更新#TextArea1 on每个按键并且不会改变 #TextArea 的价值,我认为你正在寻找,但我可能会误解)

(note that this updates #TextArea1 on every keypress and doesn't change the value of #TextArea wich is what I think you're looking for, but I might be misunderstanding)

EDIT2:

如果您想了解旧功能的行为(插入< br /> s到 #TextArea )这样做:

$('#TextArea').keypress(function(evt){
        $('#TextArea').html(nl2br($('#TextArea').val())); // replace linebreaks first
        $('#TextArea1').html($('#TextArea').val()); // copy to #TextArea1
    });

这篇关于nl2br()等效于javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆