问题描述
目前我为每个 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());
}
});
推荐答案
看看这看起来正是你正在寻找的。基本上,它是:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!