Jquery:不是没有使用id

时间:2015-04-08 18:29:37

标签: jquery html

我想制作一个下拉菜单,以便在页面上的任何位置点击下拉菜单或指向它们的链接时,下拉列表将被隐藏。
Jquery的:

$('body:not(#top-links-bar)').click(function(){
   $('.dropdown').hide();
});

HTML:

    <div id="top-links-bar">

    <span  class="top-link link-bar-link " style="font-size:20pt; border:inherit;border-radius:inherit;"></span>

    <span class="top-link link-bar-link dropdown-opener" id="learn">Link One <span class="caret"></span></span>



    <span class="top-link link-bar-link dropdown-opener" id="stories-link">Link Two<span class="caret"></span></span>

    <span class="top-link link-bar-link" id="tutorials-and-snippets">Link Three<span class="caret"></span></span>

    <!---<span class="top-link link-bar-link dropdown-opener" id="affiliate-content">Link Four <span class="caret"></span></span>--->

    <a href="" style="color:blue;" style="position:relative; right:50px; top:20px;"><span class="top-link link-bar-link" id="login" >Link Five</span></a>

<a href="" style="color:blue;" style="position:relative; right:100px; top:20px;"><span class="top-link link-bar-link" id="create-account"  >Link Six</span></a>



    </div>
    <div id="learn-dropdown" class="dropdown" style="font-weight:bold;">
    <p style="font-size:20pt;">HTML and CSS
    <ul>
    <li> <a href="learn/learn-html">The Basics</a></li>
    </ul>
    </p>
    <p style="font-size:20pt;">Javascript</p>
    </div>
    <div id="affiliate-content-dropdown" class="dropdown">
   </div>   
    <div id="snippet-dropdown" class="dropdown">
   </div>
    <div id="stories-dropdown" class="dropdown">
    </div>

我还有其他代码可以让下拉列表真正下降。使用此代码,下拉列表将保持隐藏状态。 Fiddle, 和site

3 个答案:

答案 0 :(得分:1)

啊,不幸的是,那不是选择器。选择器只选择'body'元素(而不是它的子元素)所以你的:不会在那里做任何事情。 See the docs here

click函数中,您只需查询元素,例如:

$('body').click(function(){
    if ($(this).attr('id') !== 'top-links-bar') {
        $('.dropdown').hide();
    }
});

编辑:上面的错误,实际上,这将有效。谢谢@SLaks和@Huangism:

$('body').click(function(e){
    if (!$(e.target).closest().length) {
        $('.dropdown').hide();
    }
});

答案 1 :(得分:1)

你选择身体时没有id top-links-bar的selecor问题每次尝试这个都是假的

    $('body div:not(#top-links-bar)').click(function () {
        $('.dropdown').hide();
    });

我认为你接受以下评论

试试这个

$('body').click(function(e){
    if (!$(e.target).closest('#top-links-bar').length) {
        $('.dropdown').hide();
    }
});

或试试这个

 $('body').click(function(e){
        if (!$(e.target).parents('#top-links-bar').length) {
            $('.dropdown').hide();
        }
    });

答案 2 :(得分:0)

您没有使用:不正确。试试这个:

jsfiddle [http://jsfiddle.net/strannij/z5bhq9zz/6/][1]

$(document.body).children().not('#top-links-bar').click(function(){
$('.dropdown').hide();

});