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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:50:18  来源:igfitidea点击:

Loop from A to Z in jQuery

javascriptjquery

提问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

This answerdemonstrates the nice idea that you do not need a hardcoded string. In short:

这个答案展示了您不需要硬编码字符串的好主意。简而言之:

for (i = 65; i <= 90; i++) { arr[i-65] = String.fromCharCode(i).toLowerCase(); }

for (i = 65; i <= 90; i++) { arr[i-65] = String.fromCharCode(i).toLowerCase(); }

回答by German Attanasio

You can avoid having numbers like 65in your code if you just use charCodeAt()and fromCharCode().

65如果您只使用charCodeAt()和 ,则可以避免在代码中使用数字fromCharCode()

Print letters from ato z:

打印来自ato 的字母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)