对于这个混乱的标题,我很抱歉--找不到最佳的表达方式。
我有一个文本区域和单词计数,如下所示:
<textarea class="form-control caption-box" name="caption" id="caption" rows="5"></textarea>
<span class="pull-right label label-default count-message" id="count_message"></span>
然后我使用javascript显示字数统计。
$('#caption').keyup(function() {
var text_length = $('#caption').val().length;
var text_remaining = text_max - text_length;
$('#count_message').html(text_length+' characters');
});
var text_length = $('#caption').val().length;
var text_remaining = text_max - text_length;
$('#count_message').html(text_length+' characters');
我需要在页面上添加6个更多的文本,所有与字数统计功能。我可以重新创建javascript 6次,然后更改元素标识符,但这感觉效率很低。
有没有更好的方法来实现这一点?
发布于 2020-05-10 00:10:41
使用类选择文本域,并从处理程序中动态导航到关联的caption
元素。例如,如果它们相邻,你可以用.next()
const maxLength = 100;
function showRemaining() {
const currLength = $(this).val().length;
const remaining = maxLength - currLength;
$(this).next().text(remaining + ' characters');
}
$('.caption').on('input', showRemaining);
$('.caption').trigger('input');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="caption" rows="5"></textarea>
<div></div>
<textarea class="caption" rows="5"></textarea>
<div></div>
<textarea class="caption" rows="5"></textarea>
<div></div>
<textarea class="caption" rows="5"></textarea>
<div></div>
在没有jQuery的情况下,这是相当微不足道的,除非它对于其他东西是必要的,请随意将其作为依赖项删除:
const maxLength = 100;
function showRemaining() {
const currLength = this.value.length;
const remaining = maxLength - currLength;
this.nextElementSibling.textContent = remaining + ' characters';
}
for (const caption of document.querySelectorAll('.caption')) {
caption.addEventListener('input', showRemaining);
caption.dispatchEvent(new Event('input'));
}
<textarea class="caption" rows="5"></textarea>
<div></div>
<textarea class="caption" rows="5"></textarea>
<div></div>
<textarea class="caption" rows="5"></textarea>
<div></div>
<textarea class="caption" rows="5"></textarea>
<div></div>
发布于 2020-05-10 01:09:31
这是工作的最终代码:
HTML x 6
<textarea class="form-control caption-box" name="caption" id="caption" rows="5"></textarea>
<span class="pull-right label label-default count-message" id="count_message"></span>
Javascript
$('.caption-box').each(function() {
var text_length = $(this).val().length;
$(this).next().html(text_length + ' characters');
});
$('.caption-box').keyup(function() {
var text_length = $(this).val().length;
$(this).next().html(text_length + ' characters');
});
https://stackoverflow.com/questions/61699762
复制相似问题