html如何获得script中的变量值

<!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>

    

    // 这里是一个循环div 是根据testVariable的数组个数 中间显示的内容,还有图片之类的全在testVariable对象中,如何直接能够用testVariable 

    <div id="testList" style="width:100%; height:100px; background-color:#CCCCCC">



    </div>

</body>

</html>



就是在script加载完后如何能够直接在body中用testVariable这个变量,求解答,谢谢


DIEA
浏览 3391回答 1
1回答

函数式编程

...</head><body>&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // 这里是一个循环div 是根据testVariable的数组个数 中间显示的内容,还有图片之类的全在testVariable对象中,如何直接能够用testVariable&nbsp;&nbsp; &nbsp; <div id="testList" style="width:100%; height:100px; background-color:#CCCCCC">&nbsp; &nbsp; </div>&nbsp; &nbsp; <script type="text/javascript">&nbsp; &nbsp; &nbsp; &nbsp; function testResult(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var testVariable = xxxx //局部变量只能在作用域中访问&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //循环testVariable&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; forEach(...)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //最后append到#testList中&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; window.onload = testResult;&nbsp; &nbsp; </script></body></html>主要有两点:script放在body尾部, 才能访问到上面已加载的元素局部变量只能在该作用域访问, 所以就在testResult()这个方法内去处理循环出的元素, 在append到外层容器即可.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript