开发者

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();
    });

Qu开发者_开发技巧estion: 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();
});


You could give them a matching class, but that is pretty simple.


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"); });

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜