如何在元素内换行一部分文本? [英] How to wrap around part of text inside an element?

查看:106
本文介绍了如何在元素内换行一部分文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说我有这句话:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

<p>标记内的

.我想以某种方式使用javascript在单词amet周围创建一个元素,例如:

inside a <p> tag. I would like to somehow use javascript to create an element around the word amet, e.g.:

Lorem ipsum dolor sit <span>amet</span>, consectetur adipiscing elit.

有某种方法可以做到这一点吗?在实际的应用程序中,我不知道要在元素周围包含什么文本,所以我不能只修改HTML.

Is there some sort of way to do this? In the real-world application for this, I won't know what text I want to have an element around, so I can't just modify the HTML.

推荐答案

一种选择是使用replace方法.

$('p').html(function(index, oldHtml){
   return oldHtml.replace(/(amet)/g, '<span>$1</span>');
});

http://jsfiddle.net/YxMvq/

这篇关于如何在元素内换行一部分文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆