[英]Why doesn't .click work when $(document.ready(function() is loaded?
[英]Why eventhandler function in document.ready works but doesn't work when taken out?
我是Java语言的新手,我想知道下面的行为。
考虑下面的工作代码 :
<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
是在通话过程中的股利。
(另外,请注意您所使用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
是因为您不知道您尝试影响的节点是否已经渲染。
脚本在页面上按顺序执行。 因此,如果在脚本定义下还有更多div
它们将不会在$("div")
匹配。
由于脚本通常包含在标头中,因此如果您希望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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.