开发者

Correct usage of jQuery .data()

开发者 https://www.devze.com 2023-04-02 05:37 出处:网络
PLEASE NOTE I HAVE UPDATED THIS QUESTION WITH NEW DATA AND LINKS I have this code based on this documentation

PLEASE NOTE I HAVE UPDATED THIS QUESTION WITH NEW DATA AND LINKS

I have this code based on this documentation

the code works here: http://jsfiddle.net/mplungjan/7ZBxP/

but not here:

I get Error: $(this).data("orgSize") is undefined

on line width: $(this).data("orgSize").width,

  $(".ui-tooltip img.thumb")
 .live("mouseenter",function() {
    cont_left = $(".ui-tooltip").position().left; // no container until hover 
    // save this scaled down image size for later
    $(this).data("newSize",{width:this.width,height:this.height})
    $(this).parent().parent().css("z-index", 1);    
    $(开发者_JS百科this).animate({
      width: $(this).data("orgSize").width,
      height: $(this).data("orgSize").height,
      left: "-=50",
      top: "-=50"
    }, "fast");
  })

here is where I define it:

    var imageObject = $('<img/>').load(function(){
      var w = this.width;
      var h = this.height;
      var orgSize = {width:w,height:h};
      var imgId = "thumb_"+p_sPubNum;
      var actualImage = $('<img/>')
         .attr("id",imgId)
         .attr("src",sOpsUrl + sImageUrl)
         .attr("alt",loadingLabel+': '+p_sPubNum)
         .addClass("thumb");             
      // set EITHER width OR height if either is > 150
      if (w<h && w>150) actualImage.attr("width",150);
      else if (w>h && h > 150) actualImage.attr("height",150);

      $('.qTip2Image').append(actualImage);
      // save original size for later    
      $("#"+imgId).data("orgSize",orgSize);

    }).error(function() {
      if ((iPos + 1) < aPublicationNumbers.length) {
        var sNextNumber = aPublicationNumbers[(iPos + 1)];
        getImage(sNextNumber, sDirection);
      }
    }).attr("src",sOpsUrl + sImageUrl);


$('.qTip2Image').append(actualImage);
  // save original size for later    
$("#"+imgId).data("orgSize",orgSize); // <<<<<<<<<< too early

var actualImage = $('<img/>')
 .attr("id",imgId)
 .attr("src",sOpsUrl + sImageUrl)
 .attr("alt",loadingLabel+': '+p_sPubNum)
 .addClass("thumb")
 .data("orgSize",orgSize);  // <<<<<<<<<< This is much better!!!

Reason it worked in the fiddle was the much smaller DOM


It gives you undefined because you are accessing the width proerty wich is undefined since you just created the elemnt!

as you can see from this fiddle the code is correct

http://jsfiddle.net/ZL4DG/


You are not setting the src of the image how do you expect it will trigger the load event. Attach an error event handler in such case. Also you have not set any width and height to the element created so it will not have any default dimensions where there is not source set.

Where is imgId defined in your code? Where are you setting id to the newly created element? In that case how will it find $("#"+imgId)?

0

精彩评论

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

关注公众号