Javascript 将变量从悬停传递到关闭悬停
我有下面的jQuery,但是我不能得到传递给第二个函数的变量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上测试它不起作用时,我该怎么做才能将变量传递给第二个函数?只需在之外定义
$("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())
}
只需在第二个函数中声明它们。