Jquery 如何使代码更简单,如果我需要单击a eq(0)show b eq(0)hide others,a eq(1)show b eq(1)hide others。。?

Jquery 如何使代码更简单,如果我需要单击a eq(0)show b eq(0)hide others,a eq(1)show b eq(1)hide others。。?,jquery,Jquery,如何使下面的代码更简单和更少 谢谢 <div class="btn"><div>0</div><div>1</div><div>2</div></div> <div class="content"><div>0</div><div>1</div><div>2</div></div> $('.btn div

如何使下面的代码更简单和更少

谢谢

<div class="btn"><div>0</div><div>1</div><div>2</div></div>
<div class="content"><div>0</div><div>1</div><div>2</div></div>

$('.btn div:eq(0)').click(function(){
    $('.content div').hide();
    $('.content div:eq(0)').show();
});
$('.btn div:eq(1)').click(function(){
    $('.content div').hide();
    $('.content div:eq(1)').show();
});
$('.btn div:eq(2)').click(function(){
    $('.content div').hide();
    $('.content div:eq(2)').show();
});
$('.btn div:eq(3)').click(function(){
    $('.content div').hide();
    $('.content div:eq(3)').show();
});
012
012
$('.btn div:eq(0')。单击(函数(){
$('.content div').hide();
$('.content div:eq(0)').show();
});
$('.btn div:eq(1)')。单击(函数(){
$('.content div').hide();
$('.content div:eq(1)').show();
});
$('.btn div:eq(2)')。单击(函数(){
$('.content div').hide();
$('.content div:eq(2)').show();
});
$('.btn div:eq(3)')。单击(函数(){
$('.content div').hide();
$('.content div:eq(3)').show();
});
试试这个

$('.btn div').click(function(){
    $('.content div').hide();
    $('.content div:eq('+$(this).index()+')').show();
});
试试这个

$('.btn div').click(function(){
    $('.content div').hide();
    $('.content div:eq('+$(this).index()+')').show();
});


您可以这样做:

var numClicked = '';

$('.btn div').on('click', function() {
     numClicked = $('.btn div').index(this);
     $('.content div').hide();
     $('.content div').eq(numClicked).show();
});

有一种更好的方法,尽管我记不清是怎么做的。

你可以这样做:

var numClicked = '';

$('.btn div').on('click', function() {
     numClicked = $('.btn div').index(this);
     $('.content div').hide();
     $('.content div').eq(numClicked).show();
});

还有一种更好的方法,尽管我记不清它是如何完成的。

@user1775888这与我的答案大致相同,但效率较低,因为有更多的调用
$()
@ExplosionPills是的,显然您希望缓存变量,这样您只需跳入dom一次,而不是三次。有一种更好更简单的方法我就是不记得了it@user1775888这与我的答案大致相同,但效率较低,因为对
$()
@ExplosionPills()的调用较多。显然,您希望缓存变量,这样您只需跳入dom一次,而不是三次。有一种更好更简单的方法我就是不记得了