猿问

js中的for循环相关问题?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head>

    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

    <title>Document</title>

</head>

<body>

    <div id="test">

        <span>0</span>

        <span>1</span>

        <span>2</span>

        <span>3</span>

    </div>

</body>

</html>

<script type="text/javascript">

    window.addEventListener("load",init,false);

    function init(){

        spans=$("test").getElementsByTagName("span");

        for(var i=0;i<spans.length;i++)

        {

            spans[i].onclick=function(){

                alert(i);

            }

        }

    }

    function $(id){

        return document.getElementById(id);

    }

</script>

为什么单击0 1 2 3弹出的警告框都是4?

犯罪嫌疑人X
浏览 519回答 1
1回答

缥缈止盈

所有span的点击事件绑定的其实是同一个函数对象,因此显示的也是最后的i值
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答