【问题标题】:pass variable from hover to offhover将变量从悬停传递到悬停
【发布时间】:2012-05-18 18:37:31
【问题描述】:
我有下面的 jQuery,但我无法将变量传递给第二个函数
$("img").hover(function(){
var $image = $(this);
var $imageNowWidth = $image.width();
},function() {
// get variable value for $image and $imageNowWidth
});
在 jsFiddle 上测试时它不起作用,我该怎么做才能将变量传递给第二个函数?
【问题讨论】:
标签:
javascript
jquery
variables
hover
【解决方案1】:
只需在 .hover 之外定义这两个变量,然后您就可以在 mouseleave 函数中使用它们。见下文,
var $image, $imageNowWidth;
$("img").hover(function(){ //mouseenter
$image = $(this);
$imageNowWidth = $image.width();
},function() { //mouseleave
//$image and $imageNowWidth is accessible HERE
});
只是想澄清this 将在mouseleave 函数中可用,因此您可以在mouseenter 中执行相同或更多操作
【解决方案2】:
为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())
}
【解决方案3】:
在外部声明变量,以便在两个函数中都可以访问它。
var image;
var imageNowWidth;
$("img").hover(function(){
image = $(this);
imageNowWidth = $image.width();
},function() {
// get variable value for $image and $imageNowWidth
});
【解决方案4】:
使用 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
});