javascript 我如何调用 jquery 变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10759388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:57:05  来源:igfitidea点击:

How do i call jquery variables?

javascriptjqueryfunctionvariables

提问by busyPixels

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

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

回答by Selvakumar Arumugam

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

回答by VisioN

    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");
        }
    );
};?

回答by thecodeparadox

$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");
  });
};