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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…