为所有功能设置内部(文件).ready的变量?

时间:2014-04-11 19:58:34

标签: javascript jquery

jQuery真的很新,这让我感到困惑。

我将此作为示例:

$(document).ready(function(){

        $("#link1 a").hover(function(){
            var $this = $(this);
            $this.css("color", "#fff");
        });
    });

显然,这会在悬停时将#link1里面的颜色改为白色。

这就是我想要做的事情:

    $(document).ready(function(){

      var $this = $(this);

      $("#link1 a").hover(function(){
        $this.css("color", "#fff");
      });

      $("#link2 a").hover(function(){
        $this.css("color", "#f00");
      });
    });

这不起作用。

我能设置var $ this = $(this); inside(document).ready所以它适用于里面的所有函数吗?

很抱歉,如果这是一个愚蠢的问题,无法在其他任何地方找到答案。我不是100%肯定会搜索我是否诚实!

2 个答案:

答案 0 :(得分:4)

您的陈述var $this = $(this);虽然有效,但却无法满足您的需求。如果你考虑一下......这指的是$(document)

因此,如果您将代码更改为:

$(document).ready(function(){

  $("#link1 a").hover(function(){
    var $this = $(this);
    $this.css("color", "#fff");
  }); //In this case $this refers to $("#link1 a")

  $("#link2 a").hover(function(){
    var $this = $(this);
    $this.css("color", "#f00");
  }); //In this case $this refers to $("#link2 a")
});

但是,这不是必要的,因为你可以这样做:

$(document).ready(function(){

  $("#link1 a").hover(function(){
    $(this).css("color", "#fff");
  });

  $("#link2 a").hover(function(){
    $(this).css("color", "#f00");
  });
});

现在,如果你想增加$this的范围,你可以这样做:

$(a).hover(function() {
    var $this = $(this);

    //now if you wanted to check for which link is currently hovered you can say this :
    var link = $this.attr("id");
    //this will set link equal to the current id

    //NOW you can have if statements checking which link it is...
    if(link == "link1") { ... do stuff }
    if(link == "link2") { ... do other stuff }
}

另外,如果你使用的是JQuery版本的POST 1.7,你应该调用这样的事件:

$(a).on("hover", function () {
    ...some function
});

最后,不要害怕查看JQuery API以获得一些帮助......它写得很好并提供了示例

https://api.jquery.com/

答案 1 :(得分:0)

不,但你可以选择一切 -

$(document).ready(function() {

    $this = $('*'); // all elements in the DOM for this page

});

我不推荐它,你为什么要这样做?

相关问题