我有四个“了解更多”按钮,每个按钮都有一个相关的内容段落。每个段落将在开始时隐藏,然后我想要它,以便当单击其中一个按钮时,显示相关内容的段落。然后,如果单击其他按钮,则会隐藏当前显示的段落,并显示与单击第二个按钮相关联的内容段落。
我无法弄清楚使用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/
答案 0 :(得分:4)
$(document).ready(function() {
var $b = $('button.learn-more'), $p = $('p');
$b.click(function() {
var i = $b.index(this);
$p.hide().eq(i).show();
})
});
答案 1 :(得分: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();
});
});
答案 2 :(得分:0)
试试这个
HTML CODE
<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 CODE
$(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;
}
<强> DEMO 强>