开发者

Javascript: body onload event, variable exists but afterwards, it becomes undefined

Here is the best example that I can create. The value of the innerHTML appears in the alert triggered by the onload function. When it hits the document.write, the same innerHTML becomes null. Any ideas on how to get the innerHTML to appear outside the onload function? I've tried global variables and even copying the value to hidden inputs and it still comes up null.

<html>

<head>

<script language='javascript'>
 function onload_function() {
  alert(document.getElementById("sample_size").innerHTML);
 }

 document.write("this is a test: " + document.getElementById("sample_size").innerHTML);
</script>

</head>

<body onload='onload_function()'>
 <form name='form_test'>
  <table border='0' cellpadding='0' cellspacing='0'>
   <tr>
    <td id='sample_size' style='display:none'>16</td>
   </tr>
  </table开发者_运维问答>
 </form>
</body>

</html>


You should try adding the script:

<script language='javascript'>
 document.write("this is a test: " + document.getElementById("sample_size").innerHTML);
</script>

in the HTML <body> instead of the in <head>. The value/page isn't loaded yet when that javascript is evaluated in the header.


instead of using a global var try putting it into a hidden input element with a unique id so you can get it with the other function using getElementByID


Without the source code, we can't really help you.

There are three possiblities here.

The variable might not actually be global.
Did you declare it with the var keyword inside the function?

The variable might be assigned to undefined elsewhere.

You may have mispelled its name.

Check the DOM tab in Firebug and see whether the variable is there and what its value is.


You can't write to the td's innerHTML outside of onload because the td doesn't yet exist until onload fires.

It works if you put the call to document.write inside your onload function:

<script language='javascript'>
 function onload_function() {
  alert(document.getElementById("sample_size").innerHTML);
  document.write("this is a test: " + document.getElementById("sample_size").innerHTML);
 } 
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜