1

我有以下代码:

<table>
<th class="title2">The <i>very</i> hungry school</th><br />
<th class="title2">The very hungry school <span>yeah it works</span></th>

和..

    function capitalise(str) {
        if (!str) return;
        var counter = 0;
        var stopWords = ['a', 'an', 'and', 'at', 'but', 'by', 'far', 'from', 'if', 'into', 'of', 'off', 'on', 'or', 'so', 'the', 'to', 'up'];
        str = str.replace(/\b\S*[a-z]+\S*\b/ig, function(match) {
            counter++;
            return $.inArray(match, stopWords) == -1 || counter === 1 ? match.substr(0, 1).toUpperCase() + match.substr(1) : match;
        });
        return str;
    }


    $('th.title2').each(function() {    

        var capclone = $(this).clone().children(':not(i)').remove().end();

        capclone.text(capitalise(capclone.text()));

        capclone.append($(this).children(':not(i)'));

        $(this).replaceWith(capclone);

    });​

这段代码适用于我需要它做的事情,但是有没有办法维护斜体元素。在它被删除的那一刻,这不是一个糟糕的解决方案,但它并不完美。

4

1 回答 1

1

如果不是使用text()usehtml()来获取 html,因为它是元素,然后将每个单词大写。我稍微简化了正则表达式/\b\w+\b/ig,它将匹配一个单词边界,后跟一个或多个字符和一个单词边界。这也将匹配 html 标记中的初始字符,但不会导致任何问题。我没有克隆和替换节点,而是更新了 html,它应该更快,因为它在 DOM 交互上更轻。

function capitalise(str) {
    if (!str) return;
    var stopWords = ['a', 'an', 'and', 'at', 'but', 'by', 'far', 'from', 'if', 'into', 'of', 'off', 'on', 'or', 'so', 'the', 'to', 'up'];
    str = str.replace(/\b\w+\b/ig, function(match) {
        return $.inArray(match, stopWords) == -1 ? match.substr(0, 1).toUpperCase() + match.substr(1) : match;
    });
    return str;
}

$('th.title2').each(function() {
    var capclone = $(this), newHtml = capitalise(capclone.html());
    capclone.html(newHtml);
});​

您可以使用这个fiddle中的代码。

于 2012-02-23T10:38:14.753 回答