简体   繁体   English

我怎么称呼jQuery变量?

[英]How do i call jquery variables?

This is very simple i am sure but i am new to jquery and am kinda stuck. 我敢肯定这很简单,但我是jquery新手,有点卡住了。

I wrote this code which works perfectly: 我写了这段代码,效果很好:

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

Then I tried to break items out into variables to make it more flexible but can't get it to work. 然后,我尝试将项目分解为变量,以使其更灵活,但无法使其正常工作。 I wrote this: 我这样写:

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

This should be exactly the same as the first code block. 这应该与第一个代码块完全相同。 Any help is much appreciated thanks 任何帮助都非常感谢

You are missing ); 您不见了); for .hover .. 对于.hover ..

$destination.hover(
   function () {
     $pin.addClass("active");
   },
   function () {
     $pin.removeClass("active");
   }
);

Also you missed $ . 您也错过了$ See below. 见下文。

var $pin = $(".image_map #cancunPin");

Full code: 完整代码:

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
    v---------- You forgot this
var $pin = $(".image_map #cancunPin");

And also you are missing ); 而且你也错过了); for .hover . .hover

So, the final version of the code: 因此,代码的最终版本:

function engageMaps() {
    var $destination = $(".destinations #cancun");
    var $pin = $(".image_map #cancunPin");
    $destination.hover(
        function() {
            $pin.addClass("active");
        }, function() {
            $pin.removeClass("active");
        }
    );
};​
$destination.hover(
    function () {
      $pin.toggleClass("active");
    });

So complete code is: 因此完整的代码是:

function engageMaps(){
  var $destination = $(".destinations #cancun");
  var $pin = $(".image_map #cancunPin"); // you use pin instead of $pin
  $destination.hover(
    function () {
      $pin.toggleClass("active");
  });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM