【问题标题】:Add <br> between text in string在字符串中的文本之间添加 <br>
【发布时间】:2014-04-30 16:13:53
【问题描述】:

我有以下功能:

var index = 0;
var text = 'Hello world!';
function type() {
  document.getElementById('screen').innerHTML += text.charAt(index);
  index += 1;
  var t = setTimeout('type()',200);
}

我想知道是否可以让它在单词 hello 和 world 之间添加一个 br 标记。

我试过这样:'hello' + br tag + 'world';但没有用,可能是因为 charAt。

谢谢

【问题讨论】:

    标签: javascript tags charat


    【解决方案1】:

    一种可能的方法:

    var index = 0;
    var text = 'Hello world!';
    var textLength = text.length;
    var elScreen = document.getElementById('screen');
    (function type() {
      var charToType = text.charAt(index);
      if (charToType === ' ') {
        charToType = '<br />';
      }
      elScreen.innerHTML += charToType;
      index += 1;
      if (index < textLength) {
        setTimeout(type, 200);
      }
    })();
    

    Demo。关键思想很简单:当接下来要处理的字符是空格时,替换为&lt;br /&gt;

    请注意这里的另外两个变化:

    • 可以使用函数引用(而不是字符串)作为 setTimeout 第一个参数。事实上,应该这样使用它。

    • 除非有很大的理由这样做,否则应该在到达末尾时停止“键入”该字符串 - 因此要检查 index &lt; textLength

    【讨论】:

    • 如果我想要一个更大的字符串,它会在每个空格中添加一个 br 标签。有什么办法可以改变吗?谢谢
    • 好吧,在这种情况下你有不同的策略。您可以定义要插入一些特殊字符的&lt;br /&gt; 的位置(保证通常不在字符串中,如this demo) - 或将&lt;br /&gt; 放在原始字符串中,并处理任何&lt;charAt 收集的符号作为此标签的标记 (demo)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 2021-12-26
    • 2021-12-20
    • 2021-12-21
    • 1970-01-01
    相关资源
    最近更新 更多