简体   繁体   中英

Hide and show elements in jQuery

Im having some menu objects, here "link1" and "link2" which I want to toggle some content (forms) on my webpage.

If form1 is visible and I click link2, I want form1 to close and form2 to open.

Relevant jQuery:

    $('#link1').click(function(){
        $('#form1:visible').hide();
        $('#form2:visible').hide();
        $('#form1:hidden').show();
    });

    $('#link2').click(function(){
        $('#form1:visible').hide();
        $('#form2:visible').hide();
        $('#form2:hidden').show();
    });

Question: How can I make this simpler?

You can use the toggle function which will switch the element between the visible and hidden states:

var f1 = $('#form1'), f2 = $('#form2');

$('#link1').click(function(){
    f1.toggle();
    f2.hide();
});

$('#link2').click(function(){
    f1.hide();
    f2.toggle();
});

Otherwise, caching the two #form selector will help make it slightly more better.

$('#link1').click(function(){
    $('#form2').hide();
    $('#form1').show();
});

$('#link2').click(function(){
    $('#form1').hide();
    $('#form2').show();
});

It hardly gets any simpler. If there's any correlation between the link clicked and the form, like the 1 and 2 in the name, you could condense it into a single function that dynamically gets the right form and shows it... Whether that's any simpler is debatable though:

$('#link1, #link2').click(function () {
    $('form').hide();
    $('#form' + this.id.substr(-1)).show();
});

您可以给他们一个匹配的类,但这很简单。

In the HTML:

<form id="form1" class="form_group1" ... >
<form id="form2" class="form_group1" ... >
...
<form id="formN" class="form_group2" ... >

In javascript:

$('#link1').click(function(){
    $('.form_group1').hide();
    $('.form_group2').show();
});

$('#link2').click(function(){
    $('.form_group2').hide();
    $('.form_group1').show();
});

I don't know if i got you right, but you have href links, and so when u click link2 you want to open form2 (in case it is not already open), and same process for link1 and form1 ?

what u can do is give a css class for each form and an id , and then: $('#link1').click(function(){ $('#idOform1').css("display","block"); $('#idOform2').css("display","none"); });

$('#link2').click(function(){ $('#idOform2').css("display","block"); $('#idOform1').css("display","none"); });

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