如何在一个span中包装每个单词,但保留文本格式 [英] How to wrap each word in a span but retain text formatting

查看:261
本文介绍了如何在一个span中包装每个单词,但保留文本格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在一个span中包装每个单词并保留文本格式?例如br,em , strong

How can I wrap each word in a span and retain text formatting? e.g. br, em, strong

我使用以下代码从富文本编辑器在一个span,但它剥离了我所有的格式。

I'm using the following code to wrap each word from a rich text editor in a span, but it's stripping out all my formatting.

$(window).load(function() {
$(".hero_image p").addClass("hero_image_caption");
$('.hero_image p').each(function(){
    var text = $(this).text().split(' ');

    for( var i = 0, len = text.length; i < len; i++ ) {
        text[i] = '<span>' + text[i] + '</span>';
        }
        $(this).html(text.join(' '));

        });        
});


推荐答案

$('.hero_image p').each(function(){
    var text = $(this).html().split(' '),
        len = text.length,
        result = []; 

    for( var i = 0; i < len; i++ ) {
        result[i] = '<span>' + text[i] + '</span>';
    }
    $(this).html(result.join(' '));
});        

这篇关于如何在一个span中包装每个单词,但保留文本格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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