Javascript在循环中的特定数量的字母后添加字母

标签 javascript jquery loops variables this

如果输入文本字段的字母超过 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/

相关文章:

javascript - 要在 Javascript 中以特殊格式列出的字符串

javascript - 使用 jQuery 移动按钮

php - 在codeigniter中插入多行mysql

java - 如何保持我的程序运行直到按下菜单上的退出? - 图书馆申请

c# - 使用 While 循环在 Xamarin Forms 中填充自定义 ListView

javascript - 来自 Google 电子表格的更快查询

javascript - 是否可以从 Redux 存储中检索特定评论评论的状态

javascript - 根据条件禁用剑道网格中的行

jquery - 这是在 JQuery 中向下滑动时淡入的正确方法吗?

php - 在 MySQL 查询中搜索第一个图像标签