简体   繁体   中英

Using the attribute selector with Jquery but results dont work fully

I have this code in my script:

function setup_buttons() {
    $('#showdiv_Home').click(function() {
        $('div[id^=div]').hide();
        $('#div1').show();
    });
    $('#showdiv_About_Overview').click(function() {
        $('div[id^=div]').hide();
        $('#div2').show();
    });
}

This is the selection in the HTML:

<li><a href="" id="showdiv_Home">| HOME |</a></li>
<li><a href="" id="showdiv_About_Overview">| ABOUT US |</a>

and this is the div's it needs to show and hide:

<!-- This is the front page -->
<div id="div1" style="display:block">
    <p> I am div 1</p>
</div>

<!-- This is the About-Company overview page -->
<div id ="div2" style="display:none;">
    <p> I am div 2</p>
</div>

I cant see anything wrong with the code but I need some of you smart people to help me out here.

When I click on my selection in changes the div display to block but only for a second and then changes itself back to hide. I cant figure out why.

Really, my question is, how do I fix it?

Do this:

$(document).ready(function(){
    $('#showdiv_Home').click(function(e){
        e.preventDefault();
        $('div[id^=div]').hide();
        $('#div1').show();
    });

    $('#showdiv_About_Overview').click(function(e){
        e.preventDefault();
        $('div[id^=div]').hide();
        $('#div2').show();
    });

});

I suggest you to not put the click events in the function like that, just do this in doc ready block:

$('li').on('click', function (e) {
    e.preventDefault();
    var idx = $(this).index() + 1;
    $('div[id^="div"]').hide();
    $('#div' + idx).show();
});

Demo with shortest way possible.

Change the href's value of anchor tag to "#". it will work for you.

 <li><a href="#" id="showdiv_Home">| HOME |</a></li>
 <li><a href="#" id="showdiv_About_Overview">| ABOUT US |</a>

working demo

you can s use this code...

function setup_buttons()
        {
            $('#showdiv_Home').click( function()
                {
                    $('#div2').hide();
                    $('#div1').show();

                });
                $('#showdiv_About_Overview').click( function()
                {
                    $('#div1').hide();
                    $('#div2").show();

                });

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM