Javascript document.getElementById, похоже, не работает - PullRequest
3 голосов
/ 09 июля 2010

У меня есть следующий код, и консоль javascript в chrome говорит: «Не удается прочитать свойство innerHTML со значением null. Почему document.getElementById ('display') оказывается с пустыми руками?

<!DOCTYPE html>
<html>
    <head>
        <title>Chat 3</title>
        <script type="text/javascript">
            function showmsg(str){
                var display = document.getElementById('display');
                display.innerHTML += "<p>" + str + "</p>";
            }

            if("WebSockets" in window){
                pass;
            }else{
                showmsg("Your browser doesn't support WebSockets. Try Google Chrome.");
            }
        </script>

        <style type="text/css">
        #username { 
            padding: 0px;
            margin: 0px;
            height: 26px;
            width: 400px;
        }

        /* ADDED container div that wraps onlineusers and display */
        #container {
          margin: 10px 0;
        }

        /* use float: left to put them side-by-side */
        #display { 
            padding: 0px;
            margin: 0px;
            border-style: solid;
            border-width: 1px;
            overflow: auto;
            height: 400px;
            width: 400px;
            float: left;
        }

        #onlineusers { 
            padding: 0px;
            margin: 0px;
            height: 400px;
            width: 200px;
            border-style: solid;
            border-width: 1px;
            float: left;
        }

        /* Added container2 to wrap inputline and sendbutton */
        #container2 {
            margin: 10px 0;
        }

        #inputline { 
            padding: 0px;
            margin: 0px;
            height: 26px;
            width: 350px;
            float: left;
        }

        #sendbutton {
            padding: 0px;
            margin: 0px;
            height: 30px;
            width: 50px;
            float: left;
        }

        /* this is a well used "hack". */
        .clearfix {
          clear: both;
        }
        </style>
    </head>
    <body onload="document.getElementById("username").focus()">
            <input type="text" id="username" />
            <div id="container">
                <div id="display"></div>
                <div id="onlineusers"></div>
                <div class="clearfix"></div>
            </div>

            <div id="container2">
                <input type="text" id="inputline" length="55" />
                <input type="button" id="sendbutton" value="Send" />
            </div>
    </body>
</html>

Ответы [ 3 ]

7 голосов
/ 09 июля 2010

Переместите ваш скрипт-раздел вниз к нижней части страницы. В противном случае он выполняется до загрузки страницы.

Кстати: размещение сценариев внизу вашей страницы - даже «лучшая практика», рекомендованная Google, Yahoo & Co

6 голосов
/ 09 июля 2010

Вы звоните showmsg до загрузки всей страницы (и, следовательно, display div).Отсюда и ошибка.Вызовите его с onload, и он будет работать.

Добавьте эту функцию в <head>

function handleLoad()
{
  document.getElementById("username").focus()
  if("WebSockets" in window){
   pass;
  }else{
    showmsg("Your browser doesn't support WebSockets. Try Google Chrome.");
  }
}

и вызовите ее с onload

<body onload="handleLoad()">
2 голосов
/ 09 июля 2010

Поместите свой скрипт в конец документа :.В вашем случае страница не была полностью проанализирована в дереве DOM, но ваш скрипт выполняется в любом случае:

       <body onload="document.getElementById('username').focus()">
           <input type="text" id="username" />
           <div id="container">
               <div id="display"></div>
               <div id="onlineusers"></div>
               <div class="clearfix"></div>
           </div>

           <div id="container2">
               <input type="text" id="inputline" length="55" />
               <input type="button" id="sendbutton" value="Send" />
           </div>

           <script type="text/javascript">
           function showmsg(str){
               var display = document.getElementById('display');
               display.innerHTML += "<p>" + str + "</p>";
           }

           if("WebSockets" in window){
              pass;
           }else{
               showmsg("Your browser doesn't support WebSockets. Try Google Chrome.");
           }
       </script>
   </body>

Это также считается хорошей практикой по соображениям производительности: http://developer.yahoo.com/performance/rules.html#js_bottom

...