Why not use Javascript handlers on the body element?

后端 未结 8 1433
有刺的猬
有刺的猬 2020-12-11 05:50

As an answer to the question of \'How do you automatically set the focus to a textbox when a web page loads?\', Espo suggests using



        
相关标签:
8条回答
  • 2020-12-11 06:33

    I can see no other reason than the possible later override, which would lead to your code never being executed. Also, obtrusive javascript is not in very high regard anymore.

    You should instead assign a function listening to the event. You can do it like this:

    function onloadFocus() {
        document.getElementById('<id>').focus();
    }
    
    if (window.addEventListener) {      
        window.addEventListener('load', function(e) {onloadFocus();}, false);} 
    else if (window.attachEvent) {
        window.attachEvent('onload', function(e) {onloadFocus();}); 
    }
    

    ...or rely on a javascript framework, such as jquery, that would provide the same functionality for you.

    0 讨论(0)
  • 2020-12-11 06:33

    Another way to look at it is using an addEventListener instead of using it as an html code try JS:

    <body onLoad="document.getElementById('<id>').focus();">
    
        <body>
    
        <script>
    
         document.body.addEventListener('load', funcLoad);
    
         function funcLoad(){
    
         document.getElementById('<id>').focus();
    
        }
    
        </script>
    </body>
    

    Try it out, it might work better than other solutions.

    0 讨论(0)
提交回复
热议问题