javascript 在 jQuery 中从 A 到 Z 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23409252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loop from A to Z in jQuery
提问by Smegger
How can I loop from A to Z? I'd like to populate a select menu with the letters of the alphabet, eg
如何从 A 循环到 Z?我想用字母表的字母填充选择菜单,例如
<select>
<option>A</option>
<option>B</option>
<option>C</option>
...
<option>Z</option>
</select>
回答by Bic
Use char codes: JavaScript Char Codes
使用字符代码:JavaScript 字符代码
for (var i = 65; i <= 90; i++) {
$('#select_id_or_class').append('<option>' + String.fromCharCode(i) + '</option>');
}
回答by Smegger
You can do this with the following
您可以使用以下方法执行此操作
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
$.each(alphabet, function(letter) {
$('.example-select-menu').append($('<option>' + alphabet[letter] + '</option>'));
});
回答by Borys Generalov
回答by German Attanasio
You can avoid having numbers like 65
in your code if you just use charCodeAt()
and fromCharCode()
.
65
如果您只使用charCodeAt()
和 ,则可以避免在代码中使用数字fromCharCode()
。
Print letters from a
to z
:
打印来自a
to 的字母z
:
for(let i = 'a'.charCodeAt(0); i <= 'z'.charCodeAt(0); i++) {
$('#select_id_or_class').append(
'<option>' + String.fromCharCode(i) + '</option>'
);
}
Or:
或者:
const aCharCode = 'a'.charCodeAt(0);
for(let i = aCharCode; i <= (aCharCode + 26); i++) {
$('#select_id_or_class').append(
'<option>' + String.fromCharCode(i) + '</option>'
);
}
If you want the uppercase characters, replace 'a'.charCodeAt(0)
with 'A'.charCodeAt(0)
如果您想要大写字符,请替换'a'.charCodeAt(0)
为'A'.charCodeAt(0)