jquery:在hover()函数中传递变量?

标签 jquery variables hover global-variables scope

我可以在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/

相关文章:

javascript - 如何在网页上的谷歌地图上添加地址?

javascript - 扫描表格数据并替换html表格中的某些字符串

php - 无法获取 PHP 变量的 MySQL 表条目

html - 跨度 :hover isn't working in Firefox but works in Chrome

jquery - 绝对侧边栏比内容 clearfix 高?

python - 如何在 python 中保存 "self"变量?

bash - ${var?} 中的 bash 变量参数扩展中的问号是什么意思?

javascript - 删除 Javascript 工具提示偏移以获得更好的悬停增长效果

html - 当悬停在不同的 div 上时如何影响其他 div 属性?

javascript - 使用javascript将一个div分成2个