2012-09-06 37 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

相关问题