且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将每个单词的第一个字母包裹在 span 标签中 - javascript

更新时间:2023-02-06 19:28:24

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

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/