Working with for loop and jquery load event for multiple images return only the last loaded one props

I'm working with a `jQuery plug-in` useful to zoom the resized background images with the mouse interaction. To make it work, I thought to use an `array` of `objects` with the `width` and `height` of a `background-image` of every element I bring to it. To do this I've created an empty `img` element, set the `src` attribute to the background image, and once it's loaded getting `width` and `height`. I've thought to handle it starting in a `for loop` which prepares every image, when the jQuery event `load` is called I create the new array element with every info about the loaded image. It seems the `load` event sets the first loaded image, and apply the same properties to every element loaded after it, how can I avoid this problem? // this is a portion of the plugin var setImageSize = function (i) { return function (e) { // I use the extend method only to get different zoom animation if they are added by the user instances[i] = {id:i, element:this_obj.get(i), settings:$.extend(true, defaults, options)}; instances[i].settings.bg.url = getBackgroundUrl(i); instances[i].settings.bg.width = parseInt($(this).width()); instances[i].settings.bg.height = parseInt($(this).height()); updateDefaultValues(instances[i]); $(instances[i].element).hover(setRollOver(i), setRollOut(i)); $(window).resize(getUpdateDefaultValues(i)); $('#debug').html($('#debug').html() + 'image loaded: ' + i + ' url:' + instances[i].settings.bg.url +'
width: '+ instances[i].settings.bg.width +' height: '+ instances[i].settings.bg.height +'
- - - - -
'); $(this).remove(); } } var prepareImageSize = function (i) { var img = $(''); img.hide(); img.bind('load', setImageSize(i)); $('body').append(img); img.attr('src', getBackgroundUrl(i)); } var init = function () { for (var i = 0; i < this_obj.length; i ++) { prepareImageSize (i); } } init(); I've reported a full working example here at http://jsfiddle.net/tonino/CFPTa/ In the plug-in I've added a script to see how the images are set, then if you try to interact with the images you'll notice the props of every images are overwritten by the last loaded image, I'm not sure how? It seems like the load event overwrite previous load event or something, how can I fix it?
Looking at your jsfiddle, I am not so sure what's not working. You appear to get different sizes for each image... at least based on the display section... what browser are you using?

以上就是Working with for loop and jquery load event for multiple images return only the last loaded one props的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » jQuery 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏