javascript - js这个哪里写的不对呢?

查看:94
本文介绍了javascript - js这个哪里写的不对呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

点哪个就让哪个变成蓝色 同时其它的都变成没有颜色呢 这样写为什么不对?

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
    #div1{width: 200px;height: 100px;}
    #div1 span{display: inline-block;width:50px;height: 30px; }
    </style>
    <script type="text/javascript">
        window.onload=function(){
            var oSm=document.getElementsByName('sm');
            for(i=0;i<oSm.length;i++){
                oSm[i].style.backgroundColor="";
                oSm[i].onclick=function(){
                    this.style.backgroundColor="blue";
                }
            }
        }
    </script>
</head>
<body>
<div id="div1">
    <span name="sm">aaa</span>
    <span name="sm">bbb</span>
</div>
</body>
</html>

解决方案

<!DOCTYPE html>
<html>
<head>

<title></title>
<style type="text/css">
    #div1{width: 200px;height: 100px;}
    #div1 span{display: inline-block;width:50px;height: 30px; }
</style>
<script type="text/javascript">
    window.onload=function(){
        var oSm=document.getElementsByName('sm');
        for(i=0;i<oSm.length;i++){
            oSm[i].style.backgroundColor="";
            oSm[i].onclick=function(){
                var _oSm=document.getElementsByName('sm');
                for(i=0;i<_oSm.length;i++) {
                    _oSm[i].style.backgroundColor = "";
                }
                this.style.backgroundColor="blue";

            }
        }
    }
</script>

</head>
<body>
<div id="div1">

<span name="sm">aaa</span>
<span name="sm">bbb</span>

</div>
</body>
</html>

这篇关于javascript - js这个哪里写的不对呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆