简体   繁体   中英

Set Variable inside (document).ready for all functions?

Really new to jQuery and this had been baffling me for a while.

I'll use this as an example:

$(document).ready(function(){

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

Obviously enough, this will change the color of the a inside #link1 to white on hover.

THIS is what I was trying to do:

    $(document).ready(function(){

      var $this = $(this);

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

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

This doesn't work.

Am I able to set var $this = $(this); inside (document).ready so it works with all functions inside it?

Sorry if this is a silly question, couldn't find an answer anywhere else. Wasn't 100% sure to search for if I'm honest!

your statement var $this = $(this); while valid, doesn't achieve what you need. If you think about it... THIS is referring to $(document)

So, if you change your code to this :

$(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")
});

however, that is not really necessary, as you can just do this :

$(document).ready(function(){

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

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

Now if you wanted to increase the scope of $this you can do something like so :

$(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 }
}

also, if you are using JQuery version POST 1.7 you should be calling events like so :

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

Lastly, don't be afraid to look at the JQuery API for some help with things... it is very well written and provides examples

https://api.jquery.com/

No, but you could select everything -

$(document).ready(function() {

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

});

I don't recommend it though, why are you doing this?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM