我正在使用流行的Firefox扩展Greasemonkey.
我想知道是否有办法以某种形式大写所有文本输入,所以如果我使用jQuery代码看起来像:
- $('form#formid input[type=text]').capitalize();
当然我知道.capitalize()不是一个有效的函数,为了大写文本你需要一个复杂的JavaScript代码,但毕竟谷歌搜索,我找不到一个似乎可以实现到Greasemonkey .
任何人都可以帮我写这个脚本吗?
通过大写,我的意思是大写每个单词的第一个字母,如CSS text-transform:capitalize;并且它必须覆盖用户可能放入的字母,也许在表单提交上更容易…
谢谢.
解决方法
- //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();
- }
- ...