[英]javascript dollar sign variable not working
I have following code in my Wordpress: 我在Wordpress中有以下代码:
(function ($) {
var $header = $("div.header");
$(window).bind("scroll resize", function () {
if ($(window).scrollTop() > 30) {
$("div.header").stop().animate({
'opacity': 0.24
}, {
duration: 1000
});
} else {
$header.stop().animate({
'opacity': 1
}, {
duration: 1000
});
}
});
})(jQuery);
If statement kicks in when supposed but else never... 如果声明在假设时开始,但从来没有......
BUT 但
If I enclose it with: 如果我附上:
jQuery(document).ready(function($) {
// code here
});
It's all fine. 一切都很好。 Why?
为什么?
Thank you 谢谢
May be you're trying to use jQuery when dom in not build. 可能是你在尝试使用jQuery而不是构建dom。 Try to use
$(document).ready
function: 尝试使用
$(document).ready
函数:
(function ($) {
$(document).ready(function () {
$header = $("div.header");
$header.remove();
});
})(jQuery);
About what you have mantioned in the question: 关于你在问题中提到的内容:
jQuery(document).ready(function ($) {
// code
});
It works because it do the same thing: it binds event handler on ready
event and pass jQuery
object as a parameter to the function as $
. 它的工作原理是因为它做同样的事情:它在
ready
事件上绑定事件处理程序,并将jQuery
对象作为参数传递给函数$
。
Now what you did before: 现在你做了什么:
(function ($) {
$header = $("div.header");
$header.remove();
})(jQuery);
Here you just declare anonymous function with named $
parameter: 在这里,您只需使用命名的
$
parameter声明匿名函数:
function ($) {
}
And call it with jQuery
object as a parameter, which will be available in the function as $
: 并使用
jQuery
对象作为参数调用它,该函数将在$
函数中可用:
(function ($) {
})(jQuery);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.