为什么document.ready中的eventhandler函数能用,取出来却不能用?

Why eventhandler function in document.ready works but doesn't work when taken out?

我是 Javascript 的新手,我想知道下面的行为。

考虑下面的工作代码

 <div><br/><strong>Click Me!</strong></div>   
 <script>

    $(document).ready(function(){
        $('div').mouseenter(function(){
           $(this).fadeTo('fast',1);
        });

        $('div').mouseleave(function(){
           $(this).fadeTo('fast',0.5); 
        });

    });

 </script>

但是这个不起作用:

 <div onmouseover="fade()"><br/><strong>Click Me!</strong></div>   
 <script>

    $(document).ready(function(){

        $('div').mouseleave(function(){
           $(this).fadeTo('fast',0.5); 
        });

    });

    function fade(){
        $(this).fadeTo('fast',1);
    }
 </script>

当我只使用内联事件处理程序和函数时,为什么第二个不起作用?

提前致谢!

首先,我不会这样做。从使用现代事件处理切换到 onXyz 属性有点落后。更多信息请见下方。

但是回答为什么它不起作用的问题:在你的第二个例子中对 fade 的调用中的 this 不是 div (它是全局对象,又名window 在浏览器上)。您必须将 onmouseover 更改为:

onmouseover="fade.call(this)"

...因为 this 是通话期间的 div。

(请注意,您在第二个代码块中使用了 onmouseover,但在第一个代码块中使用了 mouseenter。我将其保留为 onmouseover,但您可能想要onmouseneter 而不是。)

示例:

$(document).ready(function(){

  $('div').mouseleave(function(){
    $(this).fadeTo('fast',0.5); 
  });

});

function fade(){
  $(this).fadeTo('fast',1);
}
<div onmouseover="fade.call(this)"><br/><strong>Click Me!</strong></div>   
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

或者,只需将 this 作为参数传入并更改 fade 以使用它:

$(document).ready(function(){

  $('div').mouseleave(function(){
    $(this).fadeTo('fast',0.5); 
  });

});

function fade(element){
  $(element).fadeTo('fast',1);
}
<div onmouseover="fade(this)"><br/><strong>Click Me!</strong></div>   
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


不过,我不会使用 onXyz 属性;如果您不希望 ready 回调中的处理程序,则不需要,但这并不意味着您必须切换到使用属性进行事件连接。相反:

$('div').mouseleave(function(){
  $(this).fadeTo('fast',0.5); 
});
$('div').mouseenter(function(){
  $(this).fadeTo('fast',1); 
});

示例:

$('div').mouseleave(function(){
  $(this).fadeTo('fast',0.5); 
});
$('div').mouseenter(function(){
  $(this).fadeTo('fast',1); 
});
<div><br/><strong>Click Me!</strong></div>   
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

您使用 document.ready 是因为您不知道您要影响的节点是否已经渲染。

脚本在页面上执行 in-order。因此,如果您的脚本定义下方有更多 div,它们将不会在 $("div").

中匹配

由于脚本通常包含在 header 中,如果您希望 JavaScript 最初看到所有节点,则完全需要 document.ready

在您的示例中,您本身不需要 document.ready。错误在别处。


<div>1</div>
<script>
  console.log($("div").length); // 1
  $(document).ready(function () {
    console.log($("div").length); // 2
  });
</script>
<div>2</div>