使用jQuery递归地将文本转换为标题大小写

时间:2016-10-10 07:49:14

标签: jquery

我正在尝试将HTML文档中的所有文本实例更改为标题大小写。这里的jQuery代码只适用于单次出现。

如何以递归方式工作? :

var ele = $('h3'); 
ele.text(toProperCase(ele.text())); 

function toProperCase(str)
{
    var noCaps = ['of','a','the','and','an','am','or','nor','but','is','if','then', 
'else','when','at','from','by','on','off','for','in','out','to','into','with'];
    return str.replace(/\w\S*/g, function(txt, offset){
        if(offset != 0 && noCaps.indexOf(txt.toLowerCase()) != -1){
            return txt.toLowerCase();    
        }
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h3>THE QUICK BROWN FOX IS ABOUT TO JUMP OVER THE FENCE</h3>

<h3 style="color: red;">HELLO THERE</h3>

1 个答案:

答案 0 :(得分:1)

.text()仅适用于第一个元素,使用循环

var ele = $('h3'); 
ele.each(function() {
    $(this).text(toProperCase($(this).text())); 
}

&#13;
&#13;
var ele = $('h3'); 
ele.each(function() { 
    $(this).text(toProperCase($(this).text())); 
});

function toProperCase(str)
{
    var noCaps = ['of','a','the','and','an','am','or','nor','but','is','if','then', 
'else','when','at','from','by','on','off','for','in','out','to','into','with'];
    return str.replace(/\w\S*/g, function(txt, offset){
        if(offset != 0 && noCaps.indexOf(txt.toLowerCase()) != -1){
            return txt.toLowerCase();    
        }
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h3>THE QUICK BROWN FOX IS ABOUT TO JUMP OVER THE FENCE</h3>

<h3 style="color: red;">HELLO THERE</h3>
&#13;
&#13;
&#13;