【问题标题】:Trying to select first item in a select box in a javascript loop [duplicate]尝试在javascript循环中选择选择框中的第一项[重复]
【发布时间】:2015-04-15 17:03:37
【问题描述】:

试图在 for 循环中关注选择列表的第一个对象。循环使用相同的 .txt 填充列表以创建多个相同的选择框

<script type="text/javascript">
for(i = 0; i < 10; i++){
    var names = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
    document.write('<tr>');
    document.write('<td>');
    document.write('Enter name '+ names[i]);
    document.write('</td>');
    document.write('<td>');
    document.write('<select id=' + names[i] + '></select>');     
    var textFile = "/names.txt";       
    jQuery.get(textFile, function(textFileData) {
        var EachName= textFileData.split("\n");
        for (q = 0; q < 10; q++) {
            var select = document.getElementById(names[q]);
            for (var j = 0, len = EachName.length; j < len; j++) {
                var option = document.createElement('option');
                   option.text = option.value = EachName[j];
                select.add(option, 0);
            };
        };
    });   
    $(document).ready(function(){
        $("select:first").focus();
    });
    document.write('</td>');
    document.write('</tr>');
};
</script>

我试图关注列表中的第一个选择对象,但无论我将 JavaScript 放在哪里,它都不会关注。我不知道我做错了什么。有什么想法吗?

【问题讨论】:

  • 那么您是要创建 10 个组合框吗?
  • 10 个包含相同值的不同选择表单对象
  • 你想关注第一个组合框的第一个元素吗?
  • 你也不需要 ;在您的for loop 末尾。
  • $(document).ready 不应在您的 for 循环中。

标签: javascript html select


【解决方案1】:

试试这样的:

$(document).ready(function(){
    for(i = 0; i < 10; i++){
        var names = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
        document.write('<tr>');
        document.write('<td>');
        document.write('Enter name '+ names[i]);
        document.write('</td>');
        document.write('<td>');
        document.write('<select id=' + names[i] + '></select>');     
        var textFile = "/names.txt";      

        jQuery.get(textFile, function(textFileData) { 
            var EachName= textFileData.split("\n");
            for (q = 0; q < 10; q++) { 
                var select = document.getElementById(names[q]);
                for (var j = 0, len = EachName.length; j < len; j++) {
                    var option = document.createElement('option');
                    option.text = option.value = EachName[j];
                    select.add(option, 0);
                }
            }
        });   
        document.write('</td>');
        document.write('</tr>');
    }
    document.getElementById("1").selectedIndex = 0;
    document.getElementById("1").focus();
});

将用于填充选择的逻辑放入document.ready 函数中...

【讨论】:

    猜你喜欢
    • 2018-04-01
    • 2018-12-01
    • 2014-08-26
    • 2014-03-11
    • 2011-11-16
    • 1970-01-01
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多