2013-06-24 75 views
0

我試圖寫一個代碼,當鼠標懸停封裝內的jQuery爲什麼動態添加圖片沒有得到顯示/ hidded懸停

我所做的是標題,將顯示一個鏈接圖標,我有一個CSS類samplea。有許多<a>class='samplea'。然後我插入jQuery以在<a>之後添加自定義鏈接圖像。我最初隱藏了圖像。然後添加jQuery,以便在標題懸停時顯示/隱藏。

但是我能夠插入圖像畢竟<a class='samplea'>但無法隱藏/顯示它們。

HTML

<h3><a class="samplea" id="aid">Sample Title</a></h3> 
<h3><a class="samplea" id="a1">Sample Title</a></h3> 
<h3><a class="samplea" id="a1">Sample Title</a></h3> 

CSS

.samplea { 
    } 

JS

$(document).ready(function() { 
     var permalinkid = 1; 
     $(".samplea").each(function (index) { 
      $(this).after("&nbsp;&nbsp;<img src='http://www.spotzerblog.com/wp-content/themes/StandardTheme_261/images/icn_permalink.png' id='permalink" + permalinkid + "' />"); 
      //if you comment below line it will show the link icons 
      //appropriately 
      $("#permalink" + permalinkid).hide();     
      $(this).hover(
        function() { $("#permalink" + permalinkid).show(); }, 
        function() { $("#permalink" + permalinkid).hide(); } 
      ); 
      permalinkid = permalinkid + 1;    
     }); 
    }); 

爲什麼會這樣呢?這裏是相應的JSFiddle

回答

3

試試這個:

// New way (jQuery 1.7+) - .on(events, selector, handler) 
$(document).on('mouseenter mouseleave', 'h3', function() { 
    $(this).find('img').toggle(); 
}); 

FIDDLE DEMO

+1

是的,工作,但是我的代碼有什麼問題? – Mahesha999

+0

這個問題很簡單。如果你看看這個[** fiddle **](http://jsfiddle.net/G3Psm/6/)並打開你的控制檯,你會發現在h3元素的懸停時,你總是會在控制檯'Mouseenter:4 Mouseleave:4',你沒有任何帶有_ID_'permalink4'的元素。發生這種情況後,由於懸停方法在最後得到jQuery的評估,當你將'permalinkid'變量設置爲4. –

0

您在每次迭代遞增permalinkid = permalinkid + 1,但是當你走了「懸停」,這將使得它只有評估它permalink4 http://jsfiddle.net/balintbako/G3Psm/5/ 的答案Palash Mondal本質上是解決你的問題,但是如果你想保持它基於ID,然後檢查: http://jsfiddle.net/balintbako/G3Psm/9/

$(document).ready(function() { 
    var permalinkid = 1; 
    $(".samplea").each(function (index) { 
     var temp = permalinkid; 
     $(this).after($("<div id='permalink" + temp + "'>text</div>")); 
     //if you comment below line it will show link icon 
     //appropriately   
     $("#permalink" + permalinkid).hide(); 
     $(this).hover(

     function() { 
      $("#permalink" + temp).show(); 
     }, 

     function() { 
      $("#permalink" + temp).hide(); 
     }); 
     permalinkid = permalinkid + 1; 
    }); 
}); 
+0

沒有得到你,請你詳細說明一下嗎? – Mahesha999

+0

檢查我的答案中的小提琴。 '$(「#permalink」+ permalinkid).show();'將是'$(「#permalink4」)。show();'當懸停發生時... –