我如何调用jquery变量?

bus*_*els 0 javascript variables jquery function

这很简单,我确定,但我是jquery的新手,有点卡住.

我写了这段完美的代码:

function engageMaps(){
  $(".destinations #cancun").hover(
    function () {
      $(".image_map #cancunPin").addClass("active");
    },
    function () {
      $(".image_map #cancunPin").removeClass("active");
    }
  );
};
Run Code Online (Sandbox Code Playgroud)

然后我尝试将项目分解为变量以使其更灵活但无法使其工作.我写了这个:

function engageMaps(){
  var $destination = $(".destinations #cancun");
  var pin = $(".image_map #cancunPin");
  $destination.hover(
    function () {
      $pin.addClass("active");
    },
    function () {
      $pin.removeClass("active");
    }
};
Run Code Online (Sandbox Code Playgroud)

这应该与第一个代码块完全相同.非常感谢任何帮助

Sel*_*gam 7

你错过);.hover..

$destination.hover(
   function () {
     $pin.addClass("active");
   },
   function () {
     $pin.removeClass("active");
   }
);
Run Code Online (Sandbox Code Playgroud)

你错过了$.见下文.

var $pin = $(".image_map #cancunPin");
Run Code Online (Sandbox Code Playgroud)

完整代码:

function engageMaps(){
  var $destination = $(".destinations #cancun");
  var $pin = $(".image_map #cancunPin"); //Added $ to pin var name as that is how it is referenced below

  $destination.hover(
    function () {
      $pin.addClass("active");
    },
    function () {
      $pin.removeClass("active");
    }
   ); //this was missing
} //removed semicolon as it is not necessary
Run Code Online (Sandbox Code Playgroud)