简体   繁体   中英

JQuery function doesn't fire on first click, but behaves as expected on all subsequent clicks

I simply need the selected link to show as selected and to show the indicated div while hiding the other two. Here's the jsfiddle:

http://jsfiddle.net/HZ4CZ/1/

Why is it not working the first click, but working every click after that?

$(document).ready(function() {
    $('ul#chooseType li a').click(function(e) {   
        $('#active').click(function(){
            $('.activeDiv').removeClass('show_hide');
            $('.inactiveDiv').addClass('show_hide');
            $('.thirdMenuDiv').addClass('show_hide');
            $('#active').addClass('selected');
            $('#inactive').removeClass('selected');
            $('#thirdMenu').removeClass('selected');
        });
        $('#inactive').click(function(){
            $('.activeDiv').addClass('show_hide');
            $('.inactiveDiv').removeClass('show_hide');
            $('.thirdMenuDiv').addClass('show_hide');
            $('#active').removeClass('selected');
            $('#inactive').addClass('selected');
            $('#thirdMenu').removeClass('selected');
        });
        $('#thirdMenu').click(function(){
            $('.activeDiv').addClass('show_hide');
            $('.inactiveDiv').addClass('show_hide');
            $('.thirdMenuDiv').removeClass('show_hide');
            $('#active').removeClass('selected');
            $('#inactive').removeClass('selected');
            $('#thirdMenu').addClass('selected');
        });

    });
});

Dont nest your click handlers! Get rid of that all encompassing handler and you're set. Fiddle: http://jsfiddle.net/tymeJV/HZ4CZ/2/

Axe this handler: $('ul#chooseType li a').click(function(e) {

It works because none of your click handlers actually get bound on page load, they get bound after the initial click.

You're installing one click handler 'ul#chooseType li a' which - when clicked - installes the other click handlers. Just remove it and it should work: http://jsfiddle.net/HZ4CZ/12/

Add a class display to all the DIVs that are used to display the tab contents. Then use DRY code like this:

$(document).ready(function() {
    $('ul#chooseType li a').click(function(e) {  
        $('ul#chooseType li a').removeClass('selected');
        $(this).addClass('selected');
        $('.display').addClass('show_hide');
        $('.display.'+this.id+'Div').removeClass('show_hide');
    });
});

FIDDLE

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