使用“for - > keyup”查询文本字段字符长度计数

时间:2013-03-23 15:01:23

标签: jquery arrays for-loop keyup

我创建了一个脚本来计算表单文本字段中的字符,但现在正在运行。我在keyup function内部发出警报以查看它是否正确,但每次i为6(表单元素的总数)。在keyup function之外,它是正确的。可能是什么问题呢?我没有看到代码有任何问题。控制台日志也是空的(没有错误)。

// Count characters
formElementsTitles = ['content_title', 'content_description', 'text_content', 'image_url', 'video_embed', 'aditional_info'];
formElementsLengths = ['100', '5000', '20000', '1000', '1000', '1000'];

for(i = 0; i < formElementsTitles.length; i++)
{   
    $('#'+formElementsTitles[i]).keyup(function() {

        charactersMax = formElementsLengths[i];
        charactersCurrent = $(this).val().length;
        charactersRemaining = charactersMax - charactersCurrent;

        if(charactersCurrent >= charactersMax)
        {
            $("#count_"+formElementsTitles[i]).html('<span class="content_count_chars_yellow">'+charactersRemaining+'</span> characters remaining');
        }
        else
        {
            $("#count_"+formElementsTitles[i]).html('<span class="content_count_chars_green">'+charactersRemaining+'</span> characters remaining');
        }
    });
}

1 个答案:

答案 0 :(得分:1)

您正在尝试在事件函数中使用i变量,这将无效,因为该函数仅在事件真正发生时执行!

这应该适合你:

var formElements = {
    content_title: {
        maxLength: 100
    }
}

for(title in formElements)
{   
    $('#'+title).keyup(function() {

        var charactersMax         = formElements[$(this).attr('id')].maxLength;
        var charactersCurrent     = $(this).val().length;
        var charactersRemaining   = charactersMax - charactersCurrent;

        if(charactersCurrent >= charactersMax)
        {
            $("#count_"+$(this).attr('id')).html('<span class="content_count_chars_yellow">'+charactersRemaining+'</span> characters remaining');
        }
        else
        {
           $("#count_"+$(this).attr('id')).html('<span class="content_count_chars_green">'+charactersRemaining+'</span> characters remaining');
        }
    });
}

请参阅此处的小提琴:http://jsfiddle.net/rA2Fm/