Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

javascript - Hide and show divs with text

I know there are a lot of these threads but none seem to really fit me.

I have 5 dives with text like "this is div1, to div5". These are always gonna be shown. And i have 5 hidden divs with text belonging to each div, that are gonna show if i click on my shown divs.

If I click div1, i want to show the hidden div1.

Right now I'm using a click function(jQuery) for every div which works but doesn't look very good in code. There has to be a better way. Any advise?

I do NOT want any of the divs to be hyperlinks, which seem to be the solution on a lot of similar threads on here.

EDIT: This is my current code.(can't get jsfiddle to work)

html

<div class="showing_div">
<p>This is a showing div</p>
</div>
<div class="hidden_div" style="display: none;>
<p>This div is hidden</p>
</div>

Jquery

$('showing_div').click(function() {

$('hidden_div').toggle();   

})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This are the most used techniques:

target element using .index() and .eq()

<div id="clickables">
    <div>CLICK 1</div>
    <div>CLICK 2</div>
</div>

<div id="togglables">
    <div>text 1</div>
    <div>text 2</div>
</div>

$(function(){

    $("#clickables div").click(function(){
         var idx = $(this).index();
         $('#togglables div').eq( idx ).slideToggle();
    });

});

Pros: you can keep a really clean HTML markup, no need to assign additional classes or ID
Cons: don't put other elements inside the parents otherwise you might mess the index count


target element using .next() or other jQuery traversal methods

<div id="menu">
    <div class="clickable">CLICK 1</div>
    <div>text 1</div>
    <div class="clickable">CLICK 2</div>
    <div>text 2</div>
</div>

$(function(){

    $("#menu .clickable").click(function(){
         $(this).next('div').slideToggle();
    });

});

target specific element using ID

    <div class="clickable" id="_1" > CLICK 1 </div>
    <div class="clickable" id="_2" > CLICK 2 </div>

    <div id="togglable_1"> text 1 </div>
    <div id="togglable_2"> text 2 </div>

$(function(){

    $(".clickable").click(function(){
         $("#togglable"+ this.id).slideToggle();
    });

});

Pros: You can target elements unlogically positioned in the DOM
Cons: Verbose HTML; Unflexible and hardly maintainable code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...