jQuery选择器问题

时间:2010-07-29 04:18:15

标签: jquery jquery-selectors

编辑 :由于下面的解决方案没有奏效,我已经包含了更多明确的代码。

我正在动态生成以下html。它基本上是一个定位的跨度,这样每当clickControl被点击时,productMenuHolder div会弹出一个菜单。在mouseleave上,菜单消失。

<span class="productControl">
    <div class="productMenuHolder" style="display:none;">
        <ul class="productMenuList">
            <li class="productMenuItem">Menu Item 1</li>
            <li class="productMenuItem">Menu Item 2</li>
            <li class="productMenuItem">Menu Item 3</li>
        </ul>
    </div>
</span>

下面是弹出菜单的jQuery示例,当鼠标离开菜单区域时隐藏它。

    //shows the hover image 
    $(".productControl").live('hover',function (){$(this).toggleClass("productControl_hover");});

    //pops the menu when productControl is clicked
    $(".productControl").live('click',function(){$(this).find('.productMenuHolder').show();});

    //hides the menu when the mouse leaves the menu
    $('.productMenuHolder').live('mouseleave',function() {$(this).hide();});

    //what i want is to hide the menu when a list item is clicked, however none of the solutions (e.g. closest, find, parent) seem to hide it!
    $('.productMenuHolder li').live('click',function(){ 
    //why are none of the solutions hiding it?
        $(this).closest('.productMenuList').hide();
        $(this).closest('.productMenuHolder').hide();
    });

3 个答案:

答案 0 :(得分:0)

只做$('.box').hide();

如果这不起作用,那么您是否尝试在代码中添加警报以查看事件是否正在触发?

或尝试两个父母,因为苹果是ul的孩子,然后你到了盒子里。

它还取决于您创建实时代码的位置。如果你在文档加载上创建它,那么它应该工作。但是,如果您在创建“.box”时创建它,那么它将无法正常工作,因为它尚未执行。

答案 1 :(得分:0)

使用.closest()

$('.apple').live('click',function(){
   $(this).closest('.box').hide();
});

或使用li

ul class="fruits" $('.fruits li').live('click',function(){ $(this).closest('.box').hide(); });
//pops the menu when productControl is clicked
$('.fruits li').live('click',function(e){ // pass e as parameter...
   e.stopPropagation();
   $(this).closest('.box').hide();
});

更新回答

$(".productControl").live('click',function(){...});

使用.stopPropagation()来阻止它的父母调用它的点击处理程序,$(".productControl").live('click',function(e){ if ($(e.target).is('li')) return; // <-- add this line... //... other codes }); 让它再次显示...


另一次更新

{{1}}

答案 2 :(得分:0)

这是最好的方法:

$('.apple').live('click', function() { 
    $(this).closest(".box").hide();
});

但使用parents也应该正常工作(区别在于:它还会隐藏.box进一步向上的DOM树。如果它不起作用,我们可能需要查看更多代码。

相关问题