不同功能的全局变量

时间:2013-05-22 20:16:52

标签: jquery html

我认为我永远不会得到关于变量的一件事是以下事情。

我有一个像这样的悬停功能:

var $thisId = $(this).attr('id');
function bindHover() {
    $("#wrapper img").hover( function() {
        console.log($thisId);
    });
}

console.log为我提供了undefined。当我在它所使用的函数之间声明变量时。现在的问题是,如果我想在我的js中拥有$(this).attr('id')所有不同的功能。我能做什么,我不必在每个函数中编写一个新变量?

2 个答案:

答案 0 :(得分:2)

var $thisId = $(this).attr('id');

这一行将 运行 $thisId将被分配一个值,代码将继续运行。

因此,当调用bindHover函数并分配处理程序时,它将使用$thisId分配的任何值。

您需要从处理程序中获取id,以便this是您想要的元素。

function bindHover() {
    $("#wrapper img").hover( function() {
        //console.log($(this).attr('id'));
        console.log(this.id); // it's shorter :-)
    });
}

答案 1 :(得分:1)

var $thisId; // create the var in global space
function bindHover() {
  $("#wrapper img").hover( function() {
    $thisId = $(this).attr('id'); // set global var in local space
    console.log($thisId); // global var displays local $(this) id
  });
  console.log($thisId); // global var retains locally defined value until set again
}