简体   繁体   中英

Why is my Javascript variable not being set outside of this function?

I am attempting to get the dimensions of an image to use later in my script. Selecting the img element directly with jQuery works fine and is easier, however it does not function in webkit browsers (the image is not loaded at the time of the function call). I'm trying to implement this solution where the variables are set after the image loads by using the jquery load() function.

Why are my variables not being set as desired?

function startSlider() {
  if (1 == 1) {
  var bImg = $('#banner img');
  var bWidth = 111, bHeight = 222;
  $("<img/>")
    .attr("src", $(bImg).attr("src"))
    .load(function() {
      bWidth = this.width;
      bHeight = this.height;
      console.log('inner: ' + this.height);
    });
  console.log('outer: ' + bHeight);
  }
}

 $(window).load(startSlider(skin));

Output

outer: 222
inner: 333

Example Source

<div id="banner">
   <img src="/path/to/image.jpg" />
</div>

.load() is an asynchronous callback, meaning it will occur at the time the browser has finished downloading the image file.

You are binding .load() to your image, then immediately logging the height. Because the .load() callback hasn't yet run, it will output the default height.

You need to wait until .load() has finished executing before continuing with any further logic that relies on the image height.

  1. startSlider() called and $("<img/>") is not ready or is not completed loaded,that's why you can't change your variable.

make sure you are using DOMContentLoaded on your code, DOMContentLoaded is event will be fire when parsing of element is finished, in jquery you can use this function

      $(document).ready(function(){
        console.log('DOM Loaded (DOMContentLoaded)');
        //place your function in here
      });

Use this:

$(document).ready(function () {
    startSlider();
});

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