我可以尝试使用make函数来显示输入标签中剩余标签的数量,但是问题是因为找不到解决方案来进行计数,
$("#keywords").on("keyup change input paste", function(e) {
var content = $("#keywords").val();
var words = content.split(",");
var num_words = words.length;
var limit = 7;
if (num_words > limit) {
var lastIndex = content.lastIndexOf(",");
$("#keywords").val(content.substring(0, lastIndex));
return false;
} else {
$(".cr_keywords").text(limit + 1 - num_words + " tags remaining");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="keywords" />
<div class="cr_keywords"></div>
应该保留“ 0个标签”
答案 0 :(得分:3)
这是解决方案
$("#keywords").on("keyup change input paste", function(e) {
var content = $("#keywords").val();
var words = content.split(",").filter(item => item);
var num_words = words.length;
var limit = 7;
if (num_words > limit) {
var lastIndex = content.lastIndexOf(",");
$("#keywords").val(content.substring(0, lastIndex));
return false;
} else {
$(".cr_keywords").text(limit - num_words + " tags remaining");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="keywords" />
<div class="cr_keywords"></div>
更新为var words = content.split(“,”)。filter(item => item);
现在它从剩余的7个标签开始,其结果符合您的预期。