2

我有四个“了解更多”按钮,每个按钮都有一段相关的内容。每个段落都将在开始时隐藏,然后我想要它,以便在单击其中一个按钮时显示相关内容的段落。然后,如果单击了不同的按钮,则当前显示的段落将被隐藏,并且与单击的第二个按钮相关联的内容段落会显示出来。

我无法弄清楚使用 jQuery 完成此任务的最佳方法是什么。

这是HTML:

<button class="learn-more">Learn More</button>
<button class="learn-more">Learn More</button>
<button class="learn-more">Learn More</button>
<button class="learn-more">Learn More</button>

<p>First paragraph</p>
<p>Second paragraph</p>
<p>Third paragraph</p>
<p>Fourth paragraph</p>

这是CSS:

p {
  display: none;        
}

这是一个带有此代码的 JSFiddle:http: //jsfiddle.net/cYFy3/3/

4

3 回答 3

4
$(document).ready(function() {
    var $b = $('button.learn-more'), $p = $('p');

    $b.click(function() {
        var i = $b.index(this);
        $p.hide().eq(i).show();
    })
});

http://jsfiddle.net/swuTP/

于 2013-01-04T05:41:35.993 回答
0
<button class="learn-more" paragraph_id="p1">Learn More</button>
<button class="learn-more" paragraph_id="p2">Learn More</button>
<button class="learn-more" paragraph_id="p3">Learn More</button>
<button class="learn-more" paragraph_id="p4">Learn More</button>

<p class="hide_paragraph" id="p1">First paragraph</p>
<p class="hide_paragraph" id="p2">Second paragraph</p>
<p class="hide_paragraph" id="p3">Third paragraph</p>
<p class="hide_paragraph" id="p4">Fourth paragraph</p>

js:

$(document).ready(function () {
     $('.learn-more').click(function(){
           $('.hide_paragraph').hide();
           $('#' + $(this).attr('paragraph_id')).show();            
     });

});

http://jsfiddle.net/CwVU7/22/

于 2013-01-04T05:53:34.437 回答
0

尝试这个

代码

<div class="btn">
<button class="learn-more">Learn More</button>
<button class="learn-more">Learn More</button>
<button class="learn-more">Learn More</button>
<button class="learn-more">Learn More</button>
</div>
<div class="pgf">
<p>First paragraph</p>
<p>Second paragraph</p>
<p>Third paragraph</p>
<p>Fourth paragraph</p>
</div>

JS代码

$(document).ready(function () {
    $('.btn button').on('click', function(){
        var btnindex = $(this).index();
        $('.pgf p').siblings('p').css({'display':'none'});
        $('.pgf p').eq(btnindex).css({'display':'block'});   
    });
});

CSS

p {
  display: none;        
}

演示

于 2013-01-04T05:58:33.210 回答