javascript - js这个哪里写的不对呢?
PHP中文网
PHP中文网 2017-04-11 10:08:24
[JavaScript讨论组]

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

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
    #p1{width: 200px;height: 100px;}
    #p1 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>
<p id="p1">
    <span name="sm">aaa</span>
    <span name="sm">bbb</span>
</p>
</body>
</html>
PHP中文网
PHP中文网

认证0级讲师

全部回复(3)
天蓬老师

<!DOCTYPE html>
<html>
<head>

<title></title>
<style type="text/css">
    #p1{width: 200px;height: 100px;}
    #p1 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>
<p id="p1">

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

</p>
</body>
</html>

巴扎黑

因为你点击的时候只执行this.style.backgroundColor="blue";这个

ringa_lee
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
    #p1{width: 200px;height: 100px;}
    #p1 span{display: inline-block;width:50px;height: 30px; }
    </style>
    <script type="text/javascript">
        window.onload=function(){
            var oSm=document.getElementsByName('sm');
            for(var i=0;i<oSm.length;i++){
                oSm[i].onclick=function(){
                    //去掉所有的样式
                    for(var j=0;j<oSm.length;j++){
                        oSm[j].style.backgroundColor='';
                    }
                    //当前的变色
                    this.style.backgroundColor="blue";
                }
            }
        }
    </script>
</head>
<body>
<p id="p1">
    <span name="sm">aaa</span>
    <span name="sm">bbb</span>
</p>
</body>
</html>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号