javascript美元符号变量不起作用 [英] javascript dollar sign variable not working

查看:31
本文介绍了javascript美元符号变量不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Wordpress中有以下代码:

I have following code in my 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...

但是

如果我将其括在其中:

jQuery(document).ready(function($) {        
  // code here
});

一切都很好.为什么?

谢谢

推荐答案

可能是您在不构建dom时尝试使用jQuery.尝试使用 $(document).ready 函数:

May be you're trying to use jQuery when dom in not build. Try to use $(document).ready function:

(function ($) {
  $(document).ready(function () {
    $header = $("div.header");
    $header.remove();
  });
})(jQuery);

关于您在问题中提到的内容:

About what you have mantioned in the question:

jQuery(document).ready(function ($) {
  // code
});

它之所以起作用是因为它执行相同的操作:它将事件处理程序绑定到 ready 事件上,并将 jQuery 对象作为参数传递给函数,作为 $ .

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 $.

现在您以前做什么:

(function ($) {
  $header = $("div.header");
  $header.remove();
})(jQuery);

在这里,您只需使用名为 $ 的参数声明匿名函数:

Here you just declare anonymous function with named $ parameter:

function ($) {
}

并使用 jQuery 对象作为参数调用它,该函数将以 $ 的形式提供:

And call it with jQuery object as a parameter, which will be available in the function as $:

(function ($) {
})(jQuery);

这篇关于javascript美元符号变量不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆