javascript - 更新我的文本区域的字符数限制

标签 javascript jquery css

所以我在这里创建了我的文本区域:

textarea {
    min-width: 120px;
    min-height: 90px;
    padding: 8px 10px;
    background: #FFF;
    border: 1px solid #E0E0E0;
    border-radius: 2px;
    outline: none;
    padding: 8px 10px;
    box-shadow: inset 0 1px 2px rgba(#E0E0E0, .50), 0 -1px 1px #FFF, 0 1px 0 #FFF;

    @include transition(all .2s ease-in-out);

    @include placeholder {
        font-family: 'Titillium Web', sans-serif;
    }
}
textarea:focus {
    border: 1px solid lighten(#3498db, 10);

    @include box-shadow(0px, 0px, 6px, rgba(lighten(#3498db, 10), .5), false);
}
.textarea-group {
    position: absolute;
    min-width: 120px;
    min-height: 90px;

    textarea[limit] {
        display: block;
        resize: none;
        border-bottom: none;
        border-bottom-left-radius: 0; border-bottom-right-radius: 0;
        margin: 0;
        position: relative;
        width: 100%;
    }
    .chars {
        display: block;
        margin: 0;
        position: relative;
        width: 100%;
        padding: 8px 10px;
        background: #FAFAFA;
        color: #999;
        font-size: 11px;
        border: 1px solid #E0E0E0;
        border-bottom-left-radius: 2px; border-bottom-right-radius: 2px;
    }
}

我已经编写了一个脚本来检测我的代码中的更改,但是它没有更新我的计数器。谁能告诉我为什么?我想可能是元素选择的问题。

$(function() {
    $('.textarea-group > textarea[limit]').keyup(function() {
        var max = $(this).attr('limit');
        var length = $(this).val().length;
        length = max - length;
        $(this + ' > .chars span').text(length);
    });
});

脚本肯定会被调用。

N.B. 我希望这适用于所有具有相同名称的元素:)

谢谢!

编辑 jquery 的最终代码如下所示:

$(function() {
    $('.textarea-group > textarea[limit]').keyup(function() {
        var max = parseInt($(this).attr('limit'));
        var length = $(this).val().length;
        length = max - length;
        $('.chars span', $(this).parent()).html(length);
    });
});

归功于 Francisco(答案)和 Akshay(整数解析)

最佳答案

this 不是字符串,因此应该会失败:

$(this + ' > .chars span')

此外,this 应该是 gextarea,因此首先您必须向上移动一个 DOM 层。

相反,请尝试使用 second parameter context :

$('.chars span', this.parentNode)

或者使用parentfind:

$(this).parent().find('.chars span')

关于javascript - 更新我的文本区域的字符数限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37643686/

相关文章:

javascript - jQuery 悬停功能有问题

javascript - 如何在加载时显示进度条,使用ajax

javascript - 无法使用 jQuery 从元素中删除类

HTML5 属性值规范化

css - 将复选框与标签对齐

javascript - 使用插值时添加换行符

javascript - 使用 jquery 禁用所有具有模态功能的页面元素

javascript - jQuery 使用 % 迭代对象

javascript - Google 可视化 API 不起作用。 (语言.html :17 Uncaught TypeError: Cannot read property 'Query' of undefined)

javascript - 脚本应在与 URL 匹配时运行