你可以解释下面的代码

时间:2010-12-16 04:05:07

标签: jquery

这是我的代码..但我无法理解这段代码。请帮助我

$('.maxlength')

    .after("<span></span>")

    .next()

    .hide()

    .end()

    .keypress(function(e) {

        var current = $(this).val().length;

        if (current >= 130) {

            if (e.which != 0 && e.which != 8) {

                e.preventDefault();

            }

        }

        $(this).next().show().text(130 - current);

    });

1 个答案:

答案 0 :(得分:6)

$('.maxlength') // select all items with class 'maxlength'

.after("<span></span>") // insert a span after 

.next() // move to the span

.hide() // hide the span

.end() // go back to originally selected element

.keypress(function(e) { // add a keypress event handler function

    var current = $(this).val().length; // get the length of the input value (a string)

    if (current >= 130) { //if it's long

        if (e.which != 0 && e.which != 8) { // and if certain keys weren't pressed (delete?)

            e.preventDefault(); // don't do what those keys would normally do - i.e. ignore the keypress

        }

    }

    $(this).next().show().text(130 - current); // show the remaining chars in the newly added span

});

...所以基本上这段代码会使文本区域的字符数限制为130个字符,并显示您可以输入多少字符。