第一个jQuery项目 - 使用变量作为选择器

and*_*amb 1 variables jquery

我想要做的事情很简单,但作为初学者,我对此感到非常沮丧.

这是我第一次尝试给你的想法.

我打算用图片做一些更有趣的事情,但我可以直接看到这不是解决方案.Mouseover正在改变图像,然后它逐渐消失,看起来很可怕.

所以,我想我可能会将所有图像放在同一个地方并将它们隐藏起来,使它们可见并在鼠标悬停在相应的热点上时将它们带到前面.我希望有一种方法可以使用.css()减少元素的z-index值.

这就是我的用武之地(同一网址,9872_gangsters_moll_2nd_attempt.html).

$(".hotspot").mouseover(function(){
          //Get the id of this triggered item
          var imageid = $(this).attr("id");
          //use it to make corresponding image id to use as jQuery selector
          var currentImg = '#img_'+ imageid;
  //      alert(currentImg);                   //shows variable is correct
  //      $('.product-img').show();            //works fine with a class
          $('currentImg').show();                //doesn't work with a variable
          $('currentImg').addClass('front');     //same, obviously
});
Run Code Online (Sandbox Code Playgroud)

我最初尝试用css切换可见性,但是使用了jQuery的show/hide.都没有奏效.问题似乎是将'currentImg'作为选择器传递.

您可以提供的任何帮助将非常感激.

谢谢,

安迪

Nic*_*ver 5

只需删除引号,使其使用文字字符串(而不是您的变量). $('currentImg')应该只是$(currentImg),像这样:

$(".hotspot").mouseover(function(){
   var currentImg = '#img_'+this.id;
   $(currentImg).show().addClass('front')
});
Run Code Online (Sandbox Code Playgroud)

上面的另一个变化......就像.idDOM属性一样,你可以直接访问它们(而不是效率较低.attr("id")).