Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将变量从悬停传递到关闭悬停_Javascript_Jquery_Variables_Hover - Fatal编程技术网

Javascript 将变量从悬停传递到关闭悬停

Javascript 将变量从悬停传递到关闭悬停,javascript,jquery,variables,hover,Javascript,Jquery,Variables,Hover,我有下面的jQuery,但是我不能得到传递给第二个函数的变量 $("img").hover(function(){ var $image = $(this); var $imageNowWidth = $image.width(); },function() { // get variable value for $image and $imageNowWidth });​ 当在JSFIDLE上测试它不起作用时,我该怎么做才能将变量传递给第二个函数?只需在之外定义

我有下面的jQuery,但是我不能得到传递给第二个函数的变量

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

当在JSFIDLE上测试它不起作用时,我该怎么做才能将变量传递给第二个函数?

只需在
之外定义这两个变量。悬停
,然后您就可以在mouseleave函数内使用它们了。见下文

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

只想澄清一下,
将在
mouseleave
函数中可用,因此您可以在
mouseenter
内部执行相同或更多操作,在外部声明变量,以便在两个函数中都可以访问它

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

使用jquery“data”方法将变量直接存储在jquery对象上:

$("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       
});​

image
imageNoWidth
定义
getter
setter
,如下所示

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())
}

只需在第二个函数中声明它们。