最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - pass variable from hover to offhover - Stack Overflow

programmeradmin1浏览0评论

/

i have the jQuery Below but i cant get the variables to pass to the second function

$("img").hover(function(){
    var $image = $(this);
    var $imageNowWidth = $image.width();
},function() {
    // get variable value for $image and $imageNowWidth   
});​

When testing on jsFiddle it doesn't work, what can I do to pass the variable to the second function?

http://jsfiddle/MwQbE/

i have the jQuery Below but i cant get the variables to pass to the second function

$("img").hover(function(){
    var $image = $(this);
    var $imageNowWidth = $image.width();
},function() {
    // get variable value for $image and $imageNowWidth   
});​

When testing on jsFiddle it doesn't work, what can I do to pass the variable to the second function?

Share Improve this question asked May 18, 2012 at 18:37 Yusaf KhaliqYusaf Khaliq 3,39311 gold badges45 silver badges82 bronze badges 1
  • Just declare them in the second function as well. – Diodeus - James MacFarlane Commented May 18, 2012 at 18:38
Add a ment  | 

4 Answers 4

Reset to default 4

Simply define those 2 variables outside .hover and then you can use them inside mouseleave function. See below,

var $image, $imageNowWidth;
$("img").hover(function(){ //mouseenter
   $image = $(this);
   $imageNowWidth = $image.width();
},function() {            //mouseleave
    //$image and $imageNowWidth is accessible HERE
});​

Just want to clarify that this will be available inside mouseleave function so you can do the same or more w.e you are doing inside mouseenter

Define getter and setter for image and imageNoWidth as below,

var getImage, getImageNoWidth;
$("img").hover(function(){
   $image = $(this);
   $imageNowWidth = $image.width();
    getImage = function(){
        return $image;
    };
    getImageNoWidth = function(){
        return $imageNowWidth;
    };
},function() {
    // get variable value for $image (getImage()) and $imageNowWidth (getImageNoWidth())
}

Declare the variable outside, so it is accessible in both functions.

var image;
var imageNowWidth;
$("img").hover(function(){
    image = $(this);
    imageNowWidth = $image.width();
},function() {
    // get variable value for $image and $imageNowWidth   
});​

Store the variable directly on the jquery object using the jquery 'data' method :

$("img").hover(function(){
    var $image = $(this);
    $image.data('imageNowWidth',$image.width());
},function() {
    var previousImageWidth = $(this).data('imageNowWidth');
    // do whatever you want to do with the width       
});​
发布评论

评论列表(0)

  1. 暂无评论