首页 > 解决方案 > 如何在以编程方式将文本添加到 Jquery 中的 html 元素后插入换行符?

问题描述

var insertTxt = $("aside p:last-of-type").text().split(" ");
insertTxt.splice(20, 0, 'Chevy Dealers Association ');
$("aside p:last-of-type").text(insertTxt);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<aside>
  <h2>Client Testimonials</h2>

  <p>Throughout the years we have worked with Vecta Corporation, we have always been amazed at the level of dedication and professionalism that they have provided us and our WGDC products. It is this commitment that has increased both our income and exposure
    exponentially.</p>

  <p>Iona Ford<br> President
  </p>
</aside>

我正在尝试以编程方式在包含在 ap html 标记中的单词 President 之后添加字符串“Chevy Dealers Association”。我遇到问题的部分是添加换行符,以便 Iona Ford、总裁和雪佛兰经销商协会各自在自己的线路上。所以我需要在 Jquery 中用这个 p html 标签创建三个单独的行。我得到的结果是将它全部显示在一行中,并在我想要换行符的地方用逗号显示。

标签: jqueryline-breaks

解决方案


我得到的结果是用逗号在一行中显示所有我想要换行符的地方

使用逗号的原因是,在将文本拆分为字符串数组后,并没有将它们重新连接成大字符串,因此输出是数组的表示形式,其中以逗号作为分隔符。

如果您希望对代码进行最少的更改并且不更改原始 html,您可以试试这个。

$("aside p:last-of-type").find("br").remove(); // remove old <br> tags as they interfere with text manipulation
var insertTxt = $("aside p:last-of-type").text().split(" ");
insertTxt.push("<br>Chevy Dealers Association"); // add new info, with <br> attached
insertTxt.splice(2, 0, "<br>"); // add <br> after "Ford"
$("aside p:last-of-type").html(insertTxt.join(" ")); // use join to add space back

也就是说,我建议您修改 html。例如,您可以为每一行添加标签并使用 id 来指示该行的含义(例如<span id="boss">Iona Ford</span>)。这可能会使将来对文本的更改变得更加容易。


推荐阅读