javascript 如何执行 setfocus(); 到下拉列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13226888/
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-26 18:07:49  来源:igfitidea点击:

how to perform setfocus(); to the dropdown list

javascriptdrop-down-menusetfocus

提问by madhu

I'm having a dropdown list which loads the records from DB on OnLoad() event, I want to set focus on the dropdown box when the page loads. I have tried many ways to set focus but its not working. pls look at the code below.

我有一个下拉列表,它在 OnLoad() 事件上从 DB 加载记录,我想在页面加载时将焦点设置在下拉框上。我尝试了很多方法来设置焦点,但它不起作用。请看下面的代码。

HTML CODE is as follows,

HTML 代码如下,

 <body onLoad="getDataSourceList()">
<div class="wrapper">   


    <form id="myUploadForm" name="myUploadForm">

    <table width="100%">
            <tr> <td align="right"><label for="dataSourceId" style=" font-family: serif; font-size: small;">DataSource Type<b style="color: red">*</b>: </label> </td> 
                 <td><select name="dataSourceType" id="dataSourceId">
                        <option value="Select"> Select</option>
                    </select>
                 </td> 
            </tr>

        </table>

    </form>



My ajax code goes below :

我的 ajax 代码如下:

function getDataSourceList() {
    $.ajax({
        url : '/DataWeb/getAllDataSources',
        type : 'post',
        dataType : 'json',
        contentType : 'application/json',

        success : function(map) {
            console.log(map);
            var select = document.getElementById("dataSourceId");
            for (index in map) {
                select.options[select.options.length] = new Option(
                        map[index], index);
            }
        },

        error : function(map) {
            console.log(map);
            console.log("error occured!!!");
        },

    });
    document.getElementById('dataSourceId').focus();
}

Thanks in advance.

提前致谢。

回答by arrest warrant

$(document).ready(function(){
 $("#myid").focus();
});

This works for me...

这对我有用...

回答by Satish N Ramteare

Try adding a tab index to dataSourceId element. refer to Which HTML elements can receive focus?for details on the elements on which focus() applies.

尝试向 dataSourceId 元素添加选项卡索引。请参阅哪些 HTML 元素可以接收焦点?有关 focus() 适用的元素的详细信息。