//add a function to jQuery so we can call it on our jQuery collections
$.fn.capitalize = function () {
//iterate through each of the elements passed in, `$.each()` is faster than `.each()
$.each(this, function () {
//split the value of this input by the spaces
var split = this.value.split(' ');
//iterate through each of the "words" and capitalize them
for (var i = 0, len = split.length; i < len; i++) {
split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
}
//re-join the string and set the value of the element
this.value = split.join(' ');
});
return this;
};
这是一个演示:http: //jsfiddle.net/jasper/qppGQ/1/
这可以在事件处理程序中使用,以始终保持大写的文本正文:
//when the user presses a key and the value of the `textarea` is changed, the new value will have all capitalized words
$('textarea').on('keyup', function () {
$(this).capitalize();
}).capitalize();//also capitalize the `textarea` element(s) on initialization
这是一个演示:http: //jsfiddle.net/jasper/qppGQ/2/
更新
要将第一个字母大写而单词的其余部分小写,我们可以.toLowerCase()
在第一个字母大写后在字符串的其余部分中使用:
...
for (var i = 0, len = split.length; i < len; i++) {
split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1).toLowerCase();
}
...
这是一个演示:http: //jsfiddle.net/jasper/qppGQ/3/