当用户在enter
标记内的<br>
标记处按<div>
键作为结果时,我应如何转换新行?
这是代码:
<textarea>
First text here //user press enter here
Second text here
</textarea>
//AJAX to insert text to Database here...
MySQL Procces
//AJAX repond here...
document.getElementById('sample').innerHTML = this.responseText;
<div>
标记内的结果
<div id='sample'>
First text here <br/>
Second text here
</div>
答案 0 :(得分:0)
在php中使用nl2br函数:
$text = nl2br($POST['text_field']);
在javascript中:
function nl2br (str, is_xhtml) {
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');
}
答案 1 :(得分:0)
您可以使用replace()
将输入(\n
)替换为<br>
Stack Snippet
var text = document.getElementById("text");
var result = document.getElementById("result");
text.addEventListener("keyup", function(e) {
result.innerHTML = text.value.replace(/\n/g, "<br />");
});
<textarea id="text"></textarea>
<div id="result"></div>