jQuery字符数 [英] jQuery character count
问题描述
我正在根据此帖子进行字符计数.
我想在窗口加载时调用该函数,但似乎遇到了问题,否则一切正常.
任何人都可以帮忙获取负载计数.
这是我的小提琴
I am working on a character count based on this post.
I would like to call the function on window load but seem to be having issues, otherwise everything works.
Can anyone lend a hand on getting the count on load please.
heres my fiddle
function countChar(val){
var len = val.value.length;
if (len >= 500) {
val.value = val.value.substring(0, 500);
$('#stat span').text(0);
}else {
$('#stat span').text(500 - len);
}
}
$(function(){
var inputT = $('#descTextArea').val();
//countChar(inputT);//this is breaking the code
$('#descTextArea').keyup(function(){
countChar(this);
});
});
推荐答案
尝试使用此方法
function countChar(val) {
var len = val.value.length;
if (len >= 500) {
val.value = val.value.substring(0, 500);
$('#stat span').text(0);
} else {
$('#stat span').text(500 - len);
}
}
countChar($('#descTextArea').get(0));
$('#descTextArea').keyup(function() {
countChar(this);
});
jsFiddle example
在您的代码中,您正在将一个字符串(值)传递给您的函数,该函数试图获取元素的长度.而是通过调用countChar($('#descTextArea').get(0));
来传递元素,并允许该函数按预期查找输入的长度.
In your code you were passing a string (the value) into your function which is trying to get the length of an element. Instead, by calling countChar($('#descTextArea').get(0));
you're just passing the element and allowing the function to find the length of the input as you intended.
这篇关于jQuery字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!