javascript文档加载顺序问题

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 6     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 7     <title>Document</title>
 8 </head>
 9 <script>
10     var a = document.getElementById("dianwo");//①位置
11     setTimeout('show()',2000);
12     function show()
13     {
14         //var a = document.getElementById("dianwo");
15         a.style.display = "block";
16         setTimeout('hiddens()',5000);
17     }
18     function hiddens()
19     {
20         //var a = document.getElementById("dianwo")
21         a.style.display = "none";
22     }
23 </script>
24 <body>
25     <input type="button" value="显示" onclick="show()">
26     <input type="button" value="隐藏" onclick="hiddens()" >
27     <img  id="dianwo" src="../Experiment 2/four.jpg" style="display:none">
28 </body>
29 </html>

文档加载顺序为从上到下,所以当①位置执行时,下面的图片还未加载,所以无法获取,a的值为NULL,所以无法完成相应的程序要求;

解决方案

第一种:把该script放在图片加载的后面,这样就可以获取

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <input type="button" value="显示" onclick="show()">
    <input type="button" value="隐藏" onclick="hiddens()" >
    <img  id="dianwo" src="../Experiment 2/four.jpg" style="display:none">
    <script>
            var a = document.getElementById("dianwo");
            setTimeout('show()',2000);
            function show()
            {
                //var a = document.getElementById("dianwo");
                a.style.display = "block";
                setTimeout('hiddens()',5000);
            }
            function hiddens()
            {
                //var a = document.getElementById("dianwo")
                a.style.display = "none";
            }
        </script>
</body>
</html>

第二种:获取图片放在调用函数中,这样调用函数时候,图片是加载完了的。可以获取

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 6     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 7     <title>Document</title>
 8 </head>
 9 <script>
10     // var a = document.getElementById("dianwo");
11     setTimeout('show()',2000);
12     function show()
13     {
14         var a = document.getElementById("dianwo");
15         a.style.display = "block";
16         setTimeout('hiddens()',5000);
17     }
18     function hiddens()
19     {
20         var a = document.getElementById("dianwo")
21         a.style.display = "none";
22     }
23 </script>
24 <body>
25     <input type="button" value="显示" onclick="show()">
26     <input type="button" value="隐藏" onclick="hiddens()" >
27     <img  id="dianwo" src="../Experiment 2/four.jpg" style="display:none">
28 </body>
29 </html>

 

posted @ 2019-01-26 10:16  jealous-boy  阅读(349)  评论(0)    收藏  举报