javascript error on internet explorer 6,7,8, “ is

2019-08-27 02:18发布

问题:

when I start my index.php it calls my javascript file that has this code below:

when the application starts immediately this error appears:

and this can only happen on the internet explorers, there is no 'txtName' on index.php, because the. js is called for every page, there any way to improve this function ? tath i dont need to put manually the js in each page?

Anyone know how can I solve this ? Thank you very much...

回答1:

Why dont you put a conditional for this method: In this case:

var iId = document.getElementById('txtName');
if(iId != null)
{
   // Processing
}


回答2:

Update:

After the updated question - you can test for the element first

function focus(){
  var txtNameObj = document.getElementById('txtName');
  if(txtNameObj){
    txtNameObj.focus();
  }
}

This should avoid the error with it not being defined.

Original

I can only guess there is one of two problems:

a.) Your DOM hasn't loaded yet (so even though that ID will exist, it doesn't yet)

b.) You do not have an element with that ID.

If the element does exist, be sure to only call the focus function once you are sure that the element is loaded. e.g. you could place it as a script tag just before the body close.

    <script>
      focus();
    </script>
  </body>
</html>