开发者

Character Counter Super Slow - jQuery

I wrote this:

$('[name=item-title]').live('keyup',function(k){
    char_limit=parseInt($('[data-charlimit]').attr('data-charlimit'));
    total = char_limit-parseInt($(this).val().length);
    $('.charcount span').text(char_limit-parseInt($(this).val().length));
});

But after the first few words it starts going super slow where I'll type and the words will show a millisecond after. If i get to like 250 words it gets nearly 3/4 of a second behind it 开发者_运维知识库seems. Any ideas why? To me what i wrote seems fairly minimal...


You're doing a DOM traversal per character and you're not sure why it's slow?

// calculate upper limit once -- it won't change, presumably
var char_limit=parseInt($('[data-charlimit]').attr('data-charlimit'));

$('[name=item-title]').live('keyup',function(k){
    // length is already numeric, no need to parse it
    var remaining = char_limit - $(this).val().length;
    $('.charcount span').text( remaining ); // use the result, note I renamed it
});


  1. If possible, precalculate the char_limit. It won't change during the typing.
  2. Use the total variable in your fourth line, or leave out its calculation completely
  3. Leave out the parseInts except for maybe the first one, they're useless.

This would give you

var char_limit=parseInt($('[data-charlimit]').attr('data-charlimit'));
$('[name=item-title]').live('keyup',function(k){
    $('.charcount span').text(char_limit-$(this).val().length);
});

I'm not sure if there are multiple char_limits though, as this would ruin those. It seems that your current $('[data-charlimit]') approach doesn't allow for those anyway.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜