How to display one div and hide all others

前端 未结 7 1182
温柔的废话
温柔的废话 2020-12-11 11:40

I want to display a div on each button click and also want to hide the other all divs how I can do it.

HTML

7条回答
  •  感动是毒
    2020-12-11 12:27

    In your JSFiddle, you are using jQuery 1.7.2. If you are using this version in your real app, you should not be using $.live(), but use $.on() instead - the former is deprecated in favour of the latter.

    The simplest and cleanest way to solve your problem would be to wrap both your buttons and divs in containers, and use $.index() to associate a button with a div:

    Note that your attributes must be quoted, as in the above HTML.

    Then, in JavaScript, you only need to bind one delegated event to the buttons container. I'll use $.on() in this case:

    $('div.buttons').on('click', 'input', function() {
        var divs = $('div.showThese').children();
    
        divs.eq($(this).index()).show().siblings().hide();
    });
    

    Here is a demo.

    The above method does away with having to use IDs and other attributes, however you will need to be careful if you want other elements in the containers, as $.index() will begin to fail if you do.

提交回复
热议问题