DIEA
2018-11-14 18:13:34
<!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這個變量,求解答,謝謝
1 回答

函數式編程
TA貢獻1807條經驗 獲得超9個贊
...
</head>
<body>
// 這里是一個循環div 是根據testVariable的數組個數 中間顯示的內容,還有圖片之類的全在testVariable對象中,如何直接能夠用testVariable
<div id="testList" style="width:100%; height:100px; background-color:#CCCCCC">
</div>
<script type="text/javascript">
function testResult(){
var testVariable = xxxx //局部變量只能在作用域中訪問
//循環testVariable
forEach(...)
//最后append到#testList中
}
window.onload = testResult;
</script>
</body>
</html>
主要有兩點:
script放在body尾部, 才能訪問到上面已加載的元素
局部變量只能在該作用域訪問, 所以就在testResult()這個方法內去處理循環出的元素, 在append到外層容器即可.
添加回答
舉報
0/150
提交
取消