限制字符jquery

Phi*_* L. 3 jquery

我想知道是否可以使用jQuery限制具有指定类的元素中的字符数量?

例如,缩短类的以下元素只显示40个左右的字符.

<p class="shortened">This would be the text limited to 40 Characters</p>
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的帮助.

Mic*_*hal 6

对于<input type="text" />元素,您只需使用该maxlength属性即可.

对于其他元素,例如<textarea>,您可以检查元素的onkeyup事件.

$('.shortened')
    .keyup(function(e){
        var $this = $(this);
        $this.text($this.text().substring(0, max)); //Set max to 40, or whatever you want
    });
Run Code Online (Sandbox Code Playgroud)

对于其他非表单元素,您可以执行相同的操作,但不必在事件处理程序上执行此操作.

$('.shortened')
    .each(function(){ 
        var remainTxt = $(this).text().substring(max, $(this).text().length);
        $(this).text($(this).text().substring(0,max));
    });
Run Code Online (Sandbox Code Playgroud)

编辑:要匹配Mark的答案,您可以存储剩余的.text()子字符串,并在用户单击"展开"按钮时附加该子字符串.