javaScript事件监听解答

点击HTML元素无法改变样式,样式是用一个函数打包的,事件监听无法调用函数


html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>title>
    <link rel="stylesheet" href="04.css">
    <style type="text/css">
       .test{
         width:80px;
         height:80px;
         background:red;
         margin-left:5px;
         float:left;
         text-align:center;
         line-height:80px;
       }     
   style>
      <script type="text/javascript" rel="script">
        function code(){
             this.style.background="yellow";
             this.style.fontSize="1.5em";
           };
         window.onload=function(){
          var a=document.getElementsByClassName("test");
           for(var i=0;ilength;i++)
              a[i].addEventListener("click",code);
              };
         };
     script>
  head>
<body>
    <div class="test">worddiv>
    <div class="test">worddiv>
    <div class="test">worddiv>
    <div class="test">worddiv>
body>
html>

31行多了个}

多了个 }; 删掉 或者for后边加一个{

img

你控制台没报错吗,for循环少了个{


 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title></title>
    <link rel="stylesheet" href="04.css">
    <style type="text/css">
       .test{
         width:80px;
         height:80px;
         background:red;
         margin-left:5px;
         float:left;
         text-align:center;
         line-height:80px;
       }     
   </style>
      <script type="text/javascript" rel="script">
        function code(){
             this.style.background="yellow";
             this.style.fontSize="1.5em";
           };
         window.onload=function(){
          var a=document.getElementsByClassName("test");
           for(var i=0;i<a.length;i++){
              a[i].addEventListener("click",code);
            };
          }
     </script>
  </head>
<body>
    <div class="test">word</div>
    <div class="test">word</div>
    <div class="test">word</div>
    <div class="test">word</div>
</body>
</html>