如果输入文本字段的字母超过 5 个,我尝试在输入文本字段中添加 br 符号。(书写时)
我的代码在 5 个字母后创建 br 符号,但它创建的 br 符号超过 1 个。
代码:
(function(i){
$('#input' + i).on('keyup', function() {
if($('#input' + i).val().length > 5) {
$('#input' + i).val($('#input' + i).val() + '<br>');
}
});
}(i))
最佳答案
我强烈建议不要这样做(似乎是对该问题的评论)。
但如果您确实想要,请使用 input
,不是keyup
,删除之前的<br>
您添加的标记,并分解整个字符串,而不是仅在末尾附加。查看评论:
(function(i) {
$('#input' + i).on('input', function() {
// No need to look it up repeatedly, remember the jQuery wrapper for this input
var $this = $(this);
// Get the value
var val = $this.val();
if (val.length > 5) {
// Remove old <br>s
val = val.replace(/<br>/g, "");
// Add new ones
var result = "";
while (val) {
result += val.substring(0, 5);
val = val.substring(5);
if (val) {
result += "<br>";
}
}
// Set the value
$this.val(result);
}
});
}(0))
<input type="text" id="input0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
关于Javascript在循环中的特定数量的字母后添加字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40993691/