将某个类中每个单词的首字母大写

Iai*_*son 3 javascript forms jquery

是否可以使用jQuery/javascript将某个类名中每个单词的首字母大写?我只想把标有"资本"类的所有字段中每个单词的第一个字母大写.

我只是希望它在键入时执行,我知道你可以用css来做它但这并不好,因为它仍然以小写形式存储在DB中.

jab*_*lab 8

这是一个简单的jQuery插件,可以为你做到这一点:

$.fn.capitalise = function() {
    return this.each(function() {
        var $this = $(this),
            text = $this.text(),
            tokens = text.split(" ").filter(function(t) {return t != ""; }),
            res = [],
            i,
            len,
            component;
        for (i = 0, len = tokens.length; i < len; i++) {
            component = tokens[i];
            res.push(component.substring(0, 1).toUpperCase());
            res.push(component.substring(1));
            res.push(" "); // put space back in
        }
        $this.text(res.join(""));
    });
};
Run Code Online (Sandbox Code Playgroud)

然后打电话给:

$(".myClass").capitalise();
Run Code Online (Sandbox Code Playgroud)

这是一个有效的例子.


Dut*_*432 5

解决方案是这样的:

工作样本:http://jsfiddle.net/Py7rW/7/

$('.captial').each(function(){
    var arr = $(this).text().split(' ');
    var result = "";
    for (var x=0; x<arr.length; x++)
        result+=arr[x].substring(0,1).toUpperCase()+arr[x].substring(1)+' ';
    $(this).text(result.substring(0, result.length-1));
});
Run Code Online (Sandbox Code Playgroud)