jquery - 如何在以编程方式将文本添加到 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 标签创建三个单独的行。我得到的结果是将它全部显示在一行中,并在我想要换行符的地方用逗号显示。
解决方案
我得到的结果是用逗号在一行中显示所有我想要换行符的地方
使用逗号的原因是,在将文本拆分为字符串数组后,并没有将它们重新连接成大字符串,因此输出是数组的表示形式,其中以逗号作为分隔符。
如果您希望对代码进行最少的更改并且不更改原始 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>
)。这可能会使将来对文本的更改变得更加容易。
推荐阅读
- javascript - svg中的角度显示工具提示作为div或组件?
- python - 我的代码仅在输入低于 31 [ProjectEuler100] 问题 #10-素数求和时有效
- mysql - 角8 | 用户认证
- android - 我是否需要重新编译 TensorFlow 才能更改 android SDK 和 NDK 的版本?
- swift - “类别”(又名“OpaquePointer”)类型的值没有成员“名称”
- java - 凯撒加密。73 中的索引 73 中的数组超出范围
- docker - 可以使用 logstash.yml 文件将 logstash 容器日志配置到特定路径吗?
- firebase - Firebase/Flutter:reload() 不刷新 user.isEmailVerified
- java - 如何在 Gradle 中查看我的依赖包的所有类名?
- gstreamer - 缺少元素:MPEG4-GENERIC 音频 RTP depayloader Gstreamer