2012-09-06 42 views
2

我有一個菜單,將在PHP中生成將有可能在其中有兩個不同的子div。長話短說,php將在「li」中添加一個類名爲「showBubbles」的div,和/或另一個類名爲「hideLogo」的div。如果存在「showBubbles」div,則需要執行一個函數,如果存在「hideLogo」,則需要執行另一個函數。我怎樣才能在鼠標懸停上做到這一點? 結構看起來像這樣:如何編寫jQuery只有當一個子div有一個類

<ul> 
<li> 
    <a href="#"><img src="imagePlaceholder" /></a> 
    <div class="showBubbles"></div> 
    <div class="hideLogo"></div> 
</li> 
</ul> 
+1

,做你需要的,如果雙方的div都存在過於同時執行的功能呢? – bfavaretto

+0

是的,如果只有一個或兩個都存在,兩個功能都需要觸發 – TripsLeft

回答

5

未經測試,但這應該是訣竅。

$('ul').on('mouseover', 'li', function(e) 
{ 
    if($(this).children('div').hasClass('showBubbles')) 
    { 
     // Execute code for showBubbles div 
    } 
    else 
    { 
     // Execute code if 'showBubbles' is not present 
    } 
} 
+0

這是爲我工作的解決方案。謝謝! – TripsLeft

0

您可以檢查是否試圖用jQuery選擇它,然後檢查返回的jQuery對象的length與某一類股利。例如,對於showBubbles

var showBubblesExists = $('li .showBubbles').length > 0; 

我相信這應該指向你正確的解決方案。

0

嘗試像下面,

var sb = 0, hb = 0; 
$('li').hover(function() { 
    sb = $('.showBubbles', this).length; 
    hb = $('.hideLogo', this).length; 

    if (sb) { /*function for sb*/ } 
    if (hb) { /*function for hb*/ } 

}, function() { 

    if (sb) { 
    //function for sb 
    sb = 0; 
    } 
    if (hb) { 
    //function for hb 
    hb = 0; 
    } 
}); 
1

懸停回調函數裏面,你可以使用下面的代碼:

var showBubbles = $("li div.showBubbles").length; 
if(showBubbles > 0){ 
    // first function here 
} 

var hideLogo = $("li div.hideLogo").length; 
if(hideLogo > 0){ 
    // second function here 
} 
+0

我需要把「這個」放在那裏嗎? – TripsLeft

+0

這與其他答案一樣,除了我一次性編寫了模式'li div.hideLogo',但其他人選擇了'li'並且在回調中,其中'this'指向他們選擇的'li'其餘的模式。 結果是一樣的。 – zeacuss

0
$('ul').on('mouseover', 'li', function() { 

    $(this).find('div.showBubbles').length && showBubbles(); //calls showBubbles() 

    $(this).find('div.hideLogo').length && hideLogo(); //calls hideLogo() 

}); 
0

試試這個

JS代碼

$('li').hover(function(){ 
    if($(this).find('.showBubbles')){ 
     showBubbles(); 
    } 
    if($(this).find('.hideLogo')){ 
     hideLogo(); 
    } 
}); 

function showBubbles(){ 
    alert('showBubbles response'); 
} 

function hideLogo(){ 
    alert('hideLogo response'); 
} 

JS FIDDLE CODE

+0

@TripsLeft是代碼工作?如果需要修改,請通知。 – Codegiant

相關問題