jQuery字符数 [英] jQuery character count

查看:139
本文介绍了jQuery字符数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在根据此帖子进行字符计数.
我想在窗口加载时调用该函数,但似乎遇到了问题,否则一切正常.
任何人都可以帮忙获取负载计数.
这是我的小提琴

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示例

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆