如何计算textarea中的换行符数?
<?php
echo "<textarea value=\"\" id=\"text\" maxlength=\"200\" wrap=\"virtual\" onChange=\"test()\"></textarea>
<script>
function test()
{
var text = $('#text').val();
var lines = text.split('\n');//SyntaxError: unterminated string literal
var count = lines.length;
console.log('+'+count); // Outputs 4
}
</script>";
?>
答案 0 :(得分:2)
您需要转义\n
中的反斜杠。否则,它由PHP解释,因为它在双引号字符串中,因此它成为Javascript中的文字换行符。
var lines = text.split('\\n');
答案 1 :(得分:-1)
<textarea cols="30" id="countLines"></textarea>
var textarea = document.getElementById("countLines");
var spaces = textarea.getAttribute("cols");
textarea.onmouseout = function() {
var lines = textarea.value.split("\n");
for (var i = 0; i < lines.length; i++)
{
if (lines[i].length <= spaces) continue;
var j = 0;
var space = spaces;
while (j++ <= spaces)
{
if (lines[i].charAt(j) === " ") space = j;
}
lines[i + 1] = lines[i].substring(space + 1) + (lines[i + 1] || "");
lines[i] = lines[i].substring(0, space);
}
var count = lines.length;
};