admin管理员组

文章数量:1293787

I have several links which all use a similar function, so I want to call the function and pass it attributes from the object that made the call. How do I do this?

This is my code:

$('.flash').click(function(){
    getDimensions($(this));
    swfobject.embedSWF(fileRef, "myContent", fileWidth, fileHeight, "9.0.0");
});

function getDimensions(linkRef){
    fileHeight = $(linkRef).attr('data-height');
    fileWidth = $(linkRef).attr('data-width');
}

Am I just referencing $(this) improperly?

I have several links which all use a similar function, so I want to call the function and pass it attributes from the object that made the call. How do I do this?

This is my code:

$('.flash').click(function(){
    getDimensions($(this));
    swfobject.embedSWF(fileRef, "myContent", fileWidth, fileHeight, "9.0.0");
});

function getDimensions(linkRef){
    fileHeight = $(linkRef).attr('data-height');
    fileWidth = $(linkRef).attr('data-width');
}

Am I just referencing $(this) improperly?

Share edited May 18, 2012 at 8:05 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Apr 12, 2011 at 22:14 mheaversmheavers 30.2k62 gold badges200 silver badges326 bronze badges 2
  • Aside from the fact that the two functions municate using globals (bad!), what isn't working? It looks like it should work. – Jon Commented Apr 12, 2011 at 22:17
  • how would you write it without globals? I think that's my problem actually - I need that function to return the fileWidth and fileHeight and carry out the rest of the click function – mheavers Commented Apr 12, 2011 at 22:19
Add a ment  | 

3 Answers 3

Reset to default 6
$('.flash').click(function(){
    var dimensions = getDimensions($(this));
    swfobject.embedSWF(fileRef, "myContent", dimensions.fileWidth, dimensions.fileHeight, "9.0.0");
});


function getDimensions(linkRef){
  return { 
    fileHeight: $(linkRef).attr('data-height'),
     fileWidth: $(linkRef).attr('data-width')
  }
}

Without globals, you can return a JSON object:

$('.flash').click(function(){
   var d = getDimensions($(this));
   swfobject.embedSWF(fileRef, "myContent", d.width, d.height, "9.0.0"); }
);

function getDimensions(linkRef){
   return { "height" : $(linkRef).attr('data-height'),
            "width"  : $(linkRef).attr('data-width') }
}

Since you are already passing a jQuery object to getDimensions function, you don't need to wrap the argument, linkRef, in another $() function inside the getDimensions function.

Use this instead:

function getDimensions(linkRef){
    fileHeight = linkRef.attr('data-height');
    fileWidth = linkRef.attr('data-width');
}

本文标签: javascriptHow to pass an object reference to a function with jQueryStack Overflow