javascript中调用对象和函数之间的区别

use*_*862 5 html javascript onmouseover onmouseout

我正在写两个文件 - 一个是html,一个是JavaScript.所以要调用我做的对象

 document.getElementById("nameObj").onmouseover = changeMe;
Run Code Online (Sandbox Code Playgroud)

在我做的JavaScript文件中

changeMe = function()
{
 //and here i write the function
}
Run Code Online (Sandbox Code Playgroud)

但现在我正在尝试优化我的代码并调用一个包含对象的函数.我创建了部分(其中4个),我正在尝试用onmouseover和更改颜色onmouseout.这是html的代码:

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="style.css">
        <script src="script.js"> </script>
        <title> test 2</title>
    </head>
    <body>
        <header> </header>
        <div id="wrapper">
        <main>
        <section class="mysection" id="section1"> </section>
        <section class="mysection" id="section2"> </section>
        <section class="mysection" id="section3"> </section>
        <section class="mysection" id="section4"> </section>
        </main>
        <div class="clear"> </div>
        </div>
        <footer> </footer>
                <script>
            (function(){
                var sec = document.getElementsByClassName("mysection");
                for(var i=0; i<3; i++)
                {
                    sec[i].onmouseover=changeMe(sec[i], i);
                    sec[i].onmouseout=changeBack(sec[i]);
                }
            })();   
        </script>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

这是JS:

function changeMe(t_section, count)
{
    if(count==0)
    {
        t_section.style.background="yellow";
    }
    if(count==1)
    {
        t_section.style.background="blue";
    }
    if(count==2)
    {
        t_section.style.background="green";
    }
    if(count==3)
    {
        t_section.style.background="red";
    }
};

function changeBack(t_section)
{
    t_section.style.background="gray";
};
Run Code Online (Sandbox Code Playgroud)

但它不起作用.我做错了什么?

Dmi*_*tin 4

将您的脚本标记更改为以下代码:

(function(){
  var sec = document.getElementsByClassName("mysection");
  for(var i = 0; i < 4; i++)
  {
    sec[i].addEventListener('mouseover', function() {
      var index = i;
      return function() {
        changeMe(sec[index], index);
      };
    }());
    sec[i].addEventListener('mouseout', function() {
      var index = i;
      return function() {
        changeBack(sec[index]);
      };
    }());
  }
})();
Run Code Online (Sandbox Code Playgroud)

在此处查看有关事件侦听器的信息。
请检查这个小提琴以获取完整的工作示例。