jQuery - 计算字符的多个textareas只更新DOM中的第一个

时间:2016-01-21 19:31:24

标签: javascript jquery html

我在页面上创建多个textareas,但一次只显示一个spans

问题是我希望能够从多个textarea 更新多个$(this),以便我可以保留一个功能。有没有办法可以使用$('.send_message_text').bind('input propertychange', function (e) { var tval = $('.send_message_text').val(), tlength = tval.length, set = 1024, remain = parseInt(set - tlength); $('.chars_left').text(remain); if (remain <= 0 && e.which !== 0 && e.charCode !== 0) { $('.send_message_text').val((tval).substring(0, tlength - 1)); } });?我知道有办法实现这个目标......我只是没有看到它!

这里是FIDDLE

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="send_invite_text" class="send_message_text"></textarea>
<textarea id="send_message_text" class="send_message_text"></textarea>


<div class="chars_left_wrapper">
<span class="chars_left">1024</span>
<span> characters remaining</span>
</div>
<div class="chars_left_wrapper">
<span class="chars_left">1024</span>
<span> characters remaining</span>
</div>
SELECT *, ST_DISTANCE(geo_location, POINT(lon, lat)) AS distance 
FROM geotable 
ORDER by distance DESC
LIMIT 200;

2 个答案:

答案 0 :(得分:2)

bind事件中,您正在呼叫第一个可用的textarea。您需要使用触发事件的那个。

以下是解决方案:

$('.send_message_text').bind('input propertychange', function (e) {
     var tval = $(e.currentTarget).val(),
            tlength = tval.length,
            set = 1024,
            remain = parseInt(set - tlength);
    $('.chars_left').text(remain);
    if (remain <= 0 && e.which !== 0 && e.charCode !== 0) {
        $('.send_message_text').val((tval).substring(0, tlength - 1));
    }
});

答案 1 :(得分:2)

使用$(this)的解决方案:

$('.send_message_text').bind('input propertychange', function (e) {
     var tval = $(this).val(),
            tlength = tval.length,
            set = 1024,
            remain = parseInt(set - tlength);
    $('.chars_left').text(remain);
    if (remain <= 0 && e.which !== 0 && e.charCode !== 0) {
        $(this).val((tval).substring(0, tlength - 1));
    }
});