开发者

jQuery — Variable comparison that just doesn't work

开发者 https://www.devze.com 2023-04-11 14:40 出处:网络
EDIT: I\'ve put this in a document ready function. The images are big though, does document ready comply with large images?

EDIT: I've put this in a document ready function. The images are big though, does document ready comply with large images? you can see it not working here: http://syndex.me

This is driving me quietly insane.

var maxxxHeight = $(window).height();

$(".theImage").children('img').each(function() {
  myHeight = $(this).height();
      if ( myHeight > maxxxHeight ){
      $(this).next().text("Browser " + maxxxHeight + " image height " + myHeight);
  };
});

For some reason,

myHeight > maxxxHeight 开发者_Python百科will not come up with anyhing. There are images whose sizes are bigger, and some not. The images are not being set by CSS. Their width and height are not specified at any point in fact.

How can this be? This is a total noob question, but i'v done if's and < / > a million times before.

Thanks


I can think of several reasons this might be happening.

  1. The images may not yet be completely loaded at the time the code runs.
  2. Your images may not be direct children of the element matching your class.
  3. Your code may be running before the document is loaded and nothing matches the class yet.

My best guess is (1), in which case you should add a load handler for the images that does what you want when the image completes loading. Running the code on both document load and image load is probably in order in case the image is cached and the load event for it fires before the image load handler is applied. Image load would be necessary if the image is replaced dynamically after the document has been loaded.

NOTE: You should be scoping myHeight locally to avoid polluting the global namespace (and potential bugs due to scoping issues).

$(document).load( function() {
    var maxxxHeight = $(window).height();

    $(".theImage").children('img').each(function() {
        $(this).load( function() { // only if images can be loaded dynamically
            handleImageLoad(this);
        });
        handleImageLoad(this);
    });

    function handleImageLoad(img)
    {
        var $img = $(img),  // declare local and cache jQuery for the argument
            myHeight = $img.height();
        if ( myHeight > maxxxHeight ){
           // this is where your real code would go to make adjustments, etc.
           $img.next().text("Browser " + maxxxHeight + " image height " + myHeight);
        };
    }
});


You need to do some debugging. Since the comparison is failing, check the values of myHeight and maxxxHeight by printing them to the console. I guarantee that one of those two is not a number. In fact, one will probably be undefined.

And are you putting your jQuery code inside a $(document).ready() call?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号