js添加事件

示例,4个div,单选变色效果,

方法1:在元素标签中添加事件名用来触发函数,优点是有明确的函数名,可以重复调用在不同的位置,也可以用不同的事件触发,缺点是每一个元素都需要添加事件,比较繁琐,

<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style type="text/css">
.a{
    width:20px;
    height:20px;
    background-color:red;
    float:left;
    margin:5px;
    }
</style>
</head>

<body>
    <div class="a" onClick="show(this)"></div> <!--参数为this,代表传回的参数是元素本身-->
    <div class="a" onClick="show(this)"></div>
    <div class="a" onClick="show(this)"></div>
    <div class="a" onClick="show(this)"></div>
</body>
</html>
<script type="text/javascript">
function show(a)//设置形参接收实参
{
    var b =document.getElementsByClassName("a");//获取元素,得到元素数组
    for(var i=0;i<b.length;i++)
    {
        b[i].style.backgroundColor = "red";//for循环遍历所有元素并改变颜色为初始颜色
    }
    a.style.backgroundColor = "green";//改变当前选中的元素的颜色
}
</script>

方法2:直接定义匿名函数,优点是不用再往标签内添加点击事件,省掉了繁琐的步骤,而且函数时绑定在事件上的,不用担心出现写错函数名而无法调用的情况,缺点是只能绑定在一种事件、一个元素或一组元素集中,不方便重复调用,

<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style type="text/css">
.a{
    width:20px;
    height:20px;
    background-color:red;
    float:left;
    margin:5px;
    }
</style>
</head>

<body>
    <div class="a"></div>
    <div class="a"></div>
    <div class="a"></div>
    <div class="a"></div>
</body>
</html>
<script type="text/javascript">
var b = document.getElementsByClassName("a");//获取元素,得到的也是元素数组
for(var i=0;i<b.length;i++)//这个循环的作用是给每一个元素加上onclick事件
{
    b[i].onclick = function()//循环遍历加事件
    {
        for(var i=0;i<b.length;i++)//这个循环用来让所有元素恢复初始色
        {
            b[i].style.backgroundColor = "red";//循环遍历恢复初始色
        }
        this.style.backgroundColor = "green";//this代表元素本身,点击谁谁就是this
    }
}
</script>

  两种方法的效果一样

原文地址:https://www.cnblogs.com/zxbs12345/p/7998100.html