2011-11-16 89 views
0

我已經讀過100+這樣的話題,但不管我做了什麼,我都無法得到它,就像我想做的一樣。我的問題是我從我的script獲得我的img src="url"。當我提醒它它給了我想要的正確輸入,但是當我把它放在attr()標記中時,我只是在圖像的路徑中發佈了「imgSrc」。當我在鼠標懸停功能中對圖像進行硬編碼時,它可以正常工作。jQuery獲得與變量的IMG SRC?

繼承人我的腳本

<script> 
    $(document).ready(function(){ 

      //Hides the images 
      $('#imgwrap img').hide(); 

      //Create variables for Link & Images 
      $('a.imgflash').mouseover(function(){ 
       var linkRel  = $(this).attr('rel'); 

       $('#imgwrap img').each(function(i,ele){ 
        if($(this).attr('rel') == linkRel) { 
         var imgSrc  = $(this).attr('src'); 
        }    
       }); 

      }); 

      //Script that makes images apears 
      //Mouseover Script 
      $('a.imgflash').mouseover(function(){   
       $('#imgwrap img').attr("src", imgSrc).show(); 
      }); 
     }); 
    </script> 

而且我的繼承人HTML

<ul> 
    <li><a rel="demo1" class="imgflash" href="#">demo1</a></li> 
    <li><a rel="demo2" class="imgflash" href="#">demo2</a></li> 
    <li><a rel="demo3" class="imgflash" href="#">demo3</a></li> 
</ul> 
<div id="imgwrap" style="width:300px; height:300px; overflow:hidden;"> 
<img rel="demo1" src="images/lux.jpg"> 
    <img rel="demo2" src="images/cover.jpg"> 
    <img rel="demo3" src="images/cover2.jpg"> 
</div> 

我希望u能幫助我如何讓我的變量「IMGSRC」後就像我在我的鼠標懸停功能需要。

+0

你有兩個鼠標懸停處理程序'$( 'a.imgflash')' - 局部變量(例如imgSrc)在另一箇中不可用。爲什麼兩個?從代碼我甚至不能告訴你想要做什麼。你能解釋一下你想在鼠標上發生什麼? – James

回答

6
 var imgSrc = ''; 
     //Create variables for Link & Images 
     $('a.imgflash').mouseover(function(){ 
      var linkRel  = $(this).attr('rel'); 

      $('#imgwrap img').each(function(i,ele){ 
       if($(this).attr('rel') == linkRel) { 
        imgSrc  = $(this).attr('src'); 
       }    
      }); 

     }); 

您需要定義鼠標懸停事件功能外IMGSRC變量,因爲當你試圖將其應用到attr,它不存在。

你可以閱讀更多關於局部/全局變量在這裏:

http://www.w3schools.com/js/js_variables.asp

+1

不是''attr''棄用?改用''prop''。 –

+0

@ChristianWattengård:[不是](http://api.jquery.com/attr/) –

+0

除非你低於1.6版 –

1

沒有需要兩個鼠標懸停處理程序。讓你的第一個完成這兩個步驟:

$(document).ready(function() { 

    //Hides the images 
    $('#imgwrap img').hide(); 

    //Create variables for Link & Images 
    $('a.imgflash').mouseover(function() { 
     var linkRel = $(this).attr('rel'); 

     $('#imgwrap img').each(function(i, ele) { 
      if ($(this).attr('rel') == linkRel) { 
       $(this).show(); 
      } 
     }); 

    }); 
}); 

或者更好的是:

$(document).ready(function() { 

    //Hides the images 
    $('#imgwrap img').hide(); 

    //Create variables for Link & Images 
    $('a.imgflash').mouseover(function() { 
     var linkRel = $(this).attr('rel'); 
     $('#imgwrap img[rel="'+linkRel+'"]').show(); 
    }); 
}); 

http://jsfiddle.net/mblase75/J6aLJ/