将每个单词的第一个字母包裹在 span 标签中 - javascript [英] Wrap each first letter of each word in span tag - javascript

查看:29
本文介绍了将每个单词的第一个字母包裹在 span 标签中 - javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用javascript将具有特定css类eachword"的行中每个单词的每个第一个字母包装到span"html标签中.同时我有很好的脚本,除了一个问题,脚本转换特殊字符,如&"转换成html格式.所以,这就是我现在所拥有的:

I need to wrap each first letter of each word from line with specific css class "eachword" into "span" html tag - using the javascript. Meanwhile I have good worked script, except one issue, the script converts special characters like "&" into html format. So, here's what I have right now:

在应用脚本之前:

<a class="eachword" href="#">Models & Brands</a>

脚本:

<script type="text/javascript">
window.onload = function()
{
    var elements = document.getElementsByClassName("eachword");

    for( var i=0; i<elements.length; i++)
    {
        elements[i].innerHTML = elements[i].innerHTML.replace(/\b([a-z])([a-z]+)?\b/gim, "<span class='firstletter'>$1</span>$2");
    }
}
</script>

结果:

<a class="eachword" href="#"><span class="firstletter">Models &<span class="firstletter">a</span>mp; <span class="firstletter">Brands</span></a>

我需要这个结果:

<a class="eachword" href="#"><span class="firstletter">Models <span class="firstletter">& </span><span class="firstletter">Brands</span></a>

在head"标签中,我也包含了 jQuery 1.7.2.

In "head" tag, I also have jQuery 1.7.2 included.

那么,问题是,代码有什么问题,我哪里出错了?感谢关注,希望对您有所帮助!

So, the question is, what's wrong with the code, where did I make mistake? Thanks for attention, hope for your help!

推荐答案

这似乎对我有用,但可能有点笨拙

This seems to work for me, may be a bit clumsy though

$(document).ready(function()
{
    // For each of the eachword class
    $("a.eachword").each(function()
    {
        // Get the string (html) and split it by " " (like PHP's explode)
        var self         = $(this);
        var theText      = self.html();
        var theTextArray = theText.split(" ");

        // Cycle them
        for (var i = 0; i < theTextArray.length; i++)
        {
            // Get this particular word and split it into individual letters
            var thisWord      = theTextArray[i];
            var thisWordArray = thisWord.split("");

            // Wrap the first letter if it is not a HTML char code
            if (thisWordArray[0] != "&")
            {
                thisWordArray[0]  = "<span class='firstletter'>"+thisWordArray[0]+"</span>";
            }

            // Stitch the letters back up
            theTextArray[i] = thisWordArray.join("");
        }

        // Join the original string back up
        var result = theTextArray.join(" ");

        self.html( result );
    });
});

http://jsfiddle.net/SFgXZ/

这篇关于将每个单词的第一个字母包裹在 span 标签中 - javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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