日期:2014-05-16  浏览次数:20511 次

span 动态绑定事件
<head runat="server">
    <title></title>
 
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <span id="A1">16.39</span><br />
        <br />
        <span id="A2">11239</span> 
        <br />
        <span id="Span2">112239</span>
    </div><span id="Span1">116.39</span><br />
    </form>
</body>

<script type="text/javascript">



    var obj = document.getElementsByTagName("span");

    for (var i = 0; i < obj.length; i++) {
        var span = document.getElementById(obj[i].id);

        span.onmouseover = function() { span.style.color = "#FF9900"; };

        span.onmouseout = function() { span.style.color = "#FFFFFF"; };
    }

 

</script>

</html>


想给每个span 绑定onmouseover , onmouseout 为啥这样写有问题? 4个实现了onmouseout,只有最后一个实现了onmouseover?
javascript

------解决方案--------------------
Try this:


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head runat="server">
    <title></title>
 
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <span id="A1">16.39</span><br />
        <br />
        <span id="A2">11239</span> 
        <br />
        <span id="Span2">112239</span>
    </div><span id="Span1">116.39</span><br />
    </form>
</body>

<script type="text/javascript">

    var obj = document.getElementsByTagName("span");

    for (var i = 0; i < obj.length; i++) {
     obj[i].onmouseover = function() { this.style.color = "#FF9900"; };

     obj[i].onmouseout = function() { this.style.color = "#FFFFFF"; };
    }

</script>

</html>

------解决方案--------------------
确实就是函数中的变量作用域问题,调用函数时span根本不是你以为的span变量;另外用关键词或者html标签来做变量名不