我可以在hover()中传递变量吗?
如下面的脚本所示,我不想两次声明同一个变量 var target = xxx
并且我不想将此变量设为全局 target = xxx
bcos 我有其他函数使用这个变量名 - target。
$('.image-profile').hover(function () {
var target = $('.button-change-image-profile',this);
target.show();
},function () {
//var target = $('.button-change-image-profile',this);
target.hide();
});
所以我尝试像这样传递var },function (target) {
,当然这是错误的,但是还有其他方法来传递这个var吗?
谢谢。
最佳答案
简短版本只是在此处切换:
$('.image-profile').hover(function () {
$('.button-change-image-profile',this).toggle();
});
要使其在每个处理程序中可用(作为更通用的解决方案),请在循环时在外部定义它(例如使用 .each()
),如下所示:
$('.image-profile').each(function() {
var target = $('.button-change-image-profile',this);
$(this).hover(function () {
target.show();
},function () {
target.hide();
});
});
关于jquery:在hover()函数中传递变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4287324/