jquery悬停不按预期工作

时间:2012-04-01 13:09:52

标签: jquery hover

我有一个带子区域的导航菜单。 subnav应显示何时父li被徘徊,但我没有得到预期的结果......

HTML

<div class="nav <%= cssClass %>">
    <ul>    
        <li><a runat="server" href="http://www.synergisticsinstitute.com/">Welcome</a></li>
        <li>
            <a runat="server" href="http://www.synergisticsinstitute.com/bhot-for-men/">BHOT&trade; For Men</a>
            <div class="subnav" style="display:none;">
                <a href="http://www.synergisticsinstitute.com/bhot-for-men/research/">BHOT&trade; Research</a>
                <a href="http://www.synergisticsinstitute.com/bhot-for-men/faq/">FAQ for Men</a>
            </div>
        </li>
        <li>
            <a runat="server" class="bhot-for-women" href="http://www.synergisticsinstitute.com/bhot-for-women/">BHOT&trade; For Women</a>
            <div class="subnav" style="display:none;">
                <a href="http://www.synergisticsinstitute.com/bhot-for-women/faq/">FAQ for Women</a>
            </div>
        </li>
        <li><a runat="server" href="http://www.synergisticsinstitute.com/hcg-weight-loss/">hCG Weight Loss</a></li>
        <li><a runat="server" href="http://www.synergisticsinstitute.com/nutrition/">Nutrition</a></li>
        <li><a runat="server" href="http://www.synergisticsinstitute.com/supplements/">Supplements</a></li>
        <li><a runat="server" href="http://www.synergisticsinstitute.com/medical-director/">Meet Our Medical Director</a></li>
        <li><a runat="server" href="http://www.synergisticsinstitute.com/contact-us/">Contact Us</a></li>
    </ul>
</div>

jquery的

$(document).ready(function () {
    var $nav = $('.nav');
    $nav.find('div.subnav').each(function () {
        $(this).parent().hover(navMouseIn(this), navMouseOut(this));
    });
});

function navMouseIn(elem) {
    $(elem).show();
}

function navMouseOut(elem) {
    $(elem).hide();
}

2 个答案:

答案 0 :(得分:1)

http://jsfiddle.net/8btwV/

$(document).ready(function () {
    $('.nav div.subnav').each(function () {
        var subnav = $(this);
        subnav.parent().hover(function() {navMouseIn(subnav);},
                               function() {navMouseOut(subnav);} );
    });
});

function navMouseIn(subnav) {
    subnav.show();
}

function navMouseOut(subnav) {
    subnav.hide();
}​

你正在使用一个不必要的.find,它只是通过查看所选元素来缩小你的选择器(也见.filter)。更重要的是,您需要将这些函数回调放入异步回调中,以便稍后调用它 - 此时您的代码立即调用它们。此外,这不再引用这些回调中的jQuery元素,因此我使用subnav作为范围变量。

答案 1 :(得分:0)

在调用navMouseIn和navMouseOut时,应该将函数对象作为回调传递。基本上你将它们的返回值作为处理程序传递。您的代码应如下所示:

$(document).ready(function () {
    var $nav = $('.nav');
    $nav.find('div.subnav').each(function () {
        $(this).parent().hover(navMouseIn, navMouseOut);
    });
});

function navMouseIn() {
    $("div.subnav:first", this).show();
}

function navMouseOut() {
    $("div.subnav:first", this).hide();
}