Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - How to display one div and hide all others

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

<div id=a style="display:none">1</diV>
<div id=b style="display:none">2</diV>
<div id=c style="display:none">3</diV>
<div id=d style="display:none" >4</diV>

<input type=button value=1 id=w>
<input type=button value=2 id=x>
<input type=button value=3 id=y>
<input type=button value=4 id=z>

jQuery

$?('#w').live('click', function () {
    $('#a').css('display', 'block');
});

$('#x').live('click', function () {
    $('#b').css('display', 'block');
});

$('#y').live('click', function () {
    $('#c').css('display', 'block');
});

$('#z').live('click', function () {
    $('#d').css('display', 'block');
});

? http://jsfiddle.net/6UcDR/

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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:

<div class="showThese">
    <div id="a" style="display:none">1</div>
    <div id="b" style="display:none">2</div>
    <div id="c" style="display:none">3</div>
    <div id="d" style="display:none" >4</div>
</div>

<div class="buttons">
    <input type="button" value="1" id="w">
    <input type="button" value="2" id="x">
    <input type="button" value="3" id="y">
    <input type="button" value="4" id="z">
</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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...