javascript javascript美元符号变量不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12274410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript dollar sign variable not working
提问by daniel.tosaba
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...
If 语句在应该的时候开始,但 else 永远不会......
BUT
但
If I enclose it with:
如果我附上它:
jQuery(document).ready(function($) {
// code here
});
It's all fine. Why?
一切都很好。为什么?
Thank you
谢谢
回答by Danil Speransky
May be you're trying to use jQuery when dom in not build. Try to use $(document).ready
function:
可能是您在未构建 dom 时尝试使用 jQuery。尝试使用$(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
event上绑定事件处理程序并将jQuery
object 作为参数传递给函数$
。
Now what you did before:
现在你之前做了什么:
(function ($) {
$header = $("div.header");
$header.remove();
})(jQuery);
Here you just declare anonymous function with named $
parameter:
在这里,您只需使用命名$
参数声明匿名函数:
function ($) {
}
And call it with jQuery
object as a parameter, which will be available in the function as $
:
并使用jQuery
object 作为参数调用它,它将在函数中可用为$
:
(function ($) {
})(jQuery);