javascript textarea每行计数字符 [英] javascript textarea count characters per line
问题描述
我正在尝试计算文本区域每一行中的字符.
I'm attempting to count the characters in each line of a textarea.
我尝试修改此代码以计算音节 http://jsfiddle.net/5Zwkq/19/没有成功.任何帮助将不胜感激.
I've tried to adapt this code for counting syllable http://jsfiddle.net/5Zwkq/19/ with no success. Any help would be appreciated.
function $CharCount($input) {
$("[name=set_" + $input + "]").keyup(function() {
var arrayOfLines = $("[name=set_" + $input + "]").val().match(/[^\r\n]+/g);
var tempArr = [];
var $content;
var char;
var $result;
for (var i = 0; i < arrayOfLines.length; i++) {
$content = arrayOfLines[i];
$result = $content.val().length;
tempArr.push($result);
}
$("[name=set_" + $input + "_content]").val(tempArr);
});
}
(function($) {
$CharCount("a");
})(jQuery);
<textarea rows="8" cols="3" class="alignright" name="set_a_syllable_count" readonly="readonly" /></textarea>
<textarea rows="8" cols="30" name="set_a"></textarea>
推荐答案
.val()
在此行中导致错误:
$result = $content.val().length;
正确删除它会计算行长(至少在计算区域中).
Removing it properly counts the line lengths (at least in the calculations area).
至于计数器textarea错误,您只是将jQuery选择器弄错了.将元素set_a_syllable_count
重命名为set_a_content
.
As for the counter textarea bug, you just got the jQuery selector wrong. Rename your element set_a_syllable_count
to set_a_content
.
还有另一个问题-当textarea为空时,由于您正在检查空的regexp结果(准确地说是null
),它会引发错误.您只需要防止在没有匹配的行时计数要执行的代码:
There is one more problem - when textarea is empty, it throws an error because you are checking an empty regexp result (null
, to be precise). You simply have to prevent counting code to execute when there are no matched lines:
if (arrayOfLines !== null) { ... counting code ... }
固定代码:
function $CharCount($input) {
$("[name=set_" + $input + "]").keyup(function() {
var arrayOfLines = $("[name=set_" + $input + "]").val().match(/[^\r\n]+/g);
var tempArr = [];
var $content;
var char;
var $result;
if (arrayOfLines !== null) {
for (var i = 0; i < arrayOfLines.length; i++) {
$content = arrayOfLines[i];
$result = $content.length;
tempArr.push($result);
}
}
$("[name=set_" + $input + "_content]").val(tempArr);
});
}
(function($) {
$CharCount("a");
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<textarea rows="8" cols="3" class="alignright" name="set_a_content" readonly="readonly" /></textarea>
<textarea rows="8" cols="30" name="set_a"></textarea>
这篇关于javascript textarea每行计数字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!