我怎样才能让字符计数影响同一网页上的不同文本区域字段而不影响彼此的字符计数。我有一个 id 为 #description
和另一个 id 为 #another-description
HTML
<li><textarea name="description" id="description"></textarea>
<div><span class="character-count"></span></div></li>
<li><textarea name="another_description" id="another-description"></textarea>
<div><span class="character-count"></span></div></li>
查询
$(document).ready(function() {
var max = 4000;
$('.character-count').text('4000 characters left');
$('#description')
.keydown(function(event){
if (event.keyCode != 8 && event.keyCode != 46 && $(this).val().length >= max) {
event.preventDefault();
}
})
.keyup(function(){
var $this = $(this),
val = $this.val().slice(0, max),
val_length = val.length,
left = max - val_length;
$('.character-count').text(left + ' characters left');
$this.val(val);
});
});
最佳答案
您可以创建一个将每个变量保存在闭包中的函数:
function countCharacters( input, output, max ) {
var $input = $(input);
var $output = $(output);
$output.text(max + ' characters left');
$input
.keydown(function(event) {
if (event.keyCode != 8 &&
event.keyCode != 46 &&
$input.val().length >= max)
event.preventDefault();
})
.keyup(function() {
var val = $input.val().slice(0, max);
var left = max - val.length;
$input.val(val);
$output.text(left + ' characters left');
});
}
countCharacters('#description', '.character-count', 4000);
countCharacters('#another_description', '.character-count-2', 3000);
编辑:要专门处理相同的类,请使用兄弟选择器:
countCharacters('#description', '#description + div .character-count', 4000);
countCharacters('#another_description', '#another_description + div .character-count', 3000);
关于javascript - 如何在同一个网页上有多个字符数而不每个字符数相互影响?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33666022/