Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

jquery - query add .css if div has active class

I have trouble with this jquery code:

jQuery(document).ready(function($) {
    if ($('#left-menu').hasClass('active')){
        console.log(true);
        $("#submenu").css("display", "block");
    };
});

With this function I need to add .css display block to submenu

<ul>
    <li>
        <a class="active" id="left-menu">Test</a>
        <ul style="display: none" id="submenu">
            <li>test</li>
            <li>test</li>
        <ul>
    </li>
    <li>
        <a id="left-menu">Test 2 </a>
        <ul style="display: none" id="submenu">
            <li>test</li>
            <li>test</li>
        <ul>
    </li>
</ul>

And now I will describe where is problem. When is active first link everything is ok and jquery add .css display: block. But when is active second link jquery do not add .css display: block.

Can you someone help me? Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

IDs must be unique, so use instead: (and close all UL tags)

<ul>
    <li>
        <a class="left-menu">Test</a>
        <ul style="display: none" class="submenu">
            <li>test</li>
            <li>test</li>
        </ul>
    </li>
    <li>
        <a class="left-menu active">Test 2 </a>
        <ul style="display: none" class="submenu">
            <li>test</li>
            <li>test</li>
        </ul>
    </li>
</ul>

And then:

jQuery(document).ready(function($) {    
        $(".left-menu.active").next('.submenu').show();
});

BTW, you could use: $(".left-menu.active").next('.submenu').show();

SEE DEMO


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...