Board logo

標題: Dom的children問題 [打印本頁]

作者: asdfg703703703    時間: 2015-9-17 16:20     標題: Dom的children問題

我想要做星星評分效果,但是var starGroup = document.getElementById('star').children; 這一行瀏覽器一直跟我說找不到children,為何??
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>02dynamicStyleImg.html</title>
    <style>
        .s {
            -webkit-filter: grayscale(1);

            /*-webkit-filter: hue-rotate(200deg);*/     
                  
        }
        .n {
            -webkit-filter: grayscale(0);
            /*-webkit-filter: hue-rotate(1deg);*/
        }


    </style>

    <script>

        window.onload = starFunc;


        var starGroup = document.getElementById('star').children;

        function starFunc() {
            for (var i = 0; i < 5; i++) {
                starGroup[i].onmouseover = starHover; //把所有星星註冊moveover事件
                starGroup[i].index = i;
            };
        }

        function starHover()
        {
            var curIndex = this.index;//滑鼠移入時獲得該星星的索引
            starLight(curIndex);
        }


        function starLight(index) {
            for (var i = 0; i < starGroup.length; i++)
            {
                if (i <= index) {
                    starGroup[i].className = "s";//點亮星星
                }
                else {
                    starGroup[i].className = "n";//熄掉星星
                }
            }
        }

    </script>
</head>
<body>


    <div id="star">
        <img style="float:left" id="idstar1" tabindex="1"  src="Images/star.jpg" />
        <img style="float:left" id="idstar2" tabindex="2" src="Images/star2.jpg" />
        <img style="float:left" id="idstar3" tabindex="3" src="Images/star3.jpg" />
        <img style="float:left" id="idstar4" tabindex="4" src="Images/star4.jpg" />
        <img style="float:left" id="idstar5" tabindex="5" src="Images/star5.jpg" />
    </div>
    <p id="starNotice"></p>

</body>
</html>
作者: artmar    時間: 2015-9-20 21:22

function starFunc() {
            starGroup = document.getElementById("star1").children;
            for (var i = 0; i < 5; i++) {
                starGroup[i].onmouseover = starHover; //把所有星星註冊moveover事件
                starGroup[i].index = i;
            };
        }

window.onload直接跳到starFunc 沒有執行 var starGroup = document.getElementById("star1").children;
所以starGroup是null
去除 var 使starGroup變成global變數,starLight才呼叫的到




歡迎光臨 jsGears.com 技術論壇 - AJAX, JavaScript, jQuery, 網站開發, 前端效能優化 (http://jsgears.com/)