search

Home  >  Q&A  >  body text

javascript - How to get variable value in script in html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>xxxxx</title>
    <script type="text/javascript">


        function testResult(){
            var testVariable = xxxx // 这是个数组对象 
        }

        window.onload = testResult;
    </script>
</head>
<body>
    
    // 这里是一个循环p 是根据testVariable的数组个数 中间显示的内容,还有图片之类的全在testVariable对象中,如何直接能够用testVariable 
    <p id="testList" style="width:100%; height:100px; background-color:#CCCCCC">


    </p>
</body>
</html>


就是在script加载完后如何能够直接在body中用testVariable这个变量,求解答,谢谢
世界只因有你世界只因有你2775 days ago6139

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-05-18 10:59:13

    ...
    </head>
    <body>
        
        // 这里是一个循环p 是根据testVariable的数组个数 中间显示的内容,还有图片之类的全在testVariable对象中,如何直接能够用testVariable 
        <p id="testList" style="width:100%; height:100px; background-color:#CCCCCC">
        </p>
        <script type="text/javascript">
            function testResult(){
                var testVariable = xxxx //局部变量只能在作用域中访问
                //循环testVariable 
                forEach(...)
                
                //最后append到#testList中
            }
    
            window.onload = testResult;
        </script>
    </body>
    </html>

    There are two main points:

    1. script is placed at the end of the body to access the loaded elements above

    2. Local variables can only be accessed in this scope, so just process the looped elements in the testResult() method, and append to the outer container.

    reply
    0
  • 習慣沉默

    習慣沉默2017-05-18 10:59:13

    The idea to solve this problem is: 1. First wait for the DOM to be loaded, 2. Then execute a function, which needs to traverse the elements in the array, 3. Finally add it to the DOM

    reply
    0
  • Cancelreply