我的HTML看起来像
<h3><a href="#" title="story title">Story Title</a>
<img class="expandstory" src="/images/plus.png" /></h3>
<div class="description">Short description about the story</div>
<h3><a href="#" title="story title">Story Title</a>
<img class="expandstory" src="/images/plus.png" /></h3>
<div class="description">Short description about the story</div>
我的jquery看起来像
$('.description').hide();
$('.description:first').show();
$('.expandstory:first').attr('src','/images/minus.png');
$('.expandstory:first').addClass('collapsestory');
$(".expandstory").click(function() {
if($(this).attr('class')=='expandstory') {
$(".description").slideUp(500);
$(this).parent().nextAll('.description:first').slideToggle(500);
$(this).attr('src','/images/minus.png');
$(this).addClass('collapsestory');
$(this).removeClass('expandstory');
}
else {
$(".description").slideUp(500);
$(this).attr('src','/images/plus.png');
$(this).addClass('expandstory');
$(this).removeClass('collapsestory');
}
});
我使一个简单的事情变得更加复杂,而且当我多次扩展/折叠div时,此操作不起作用。
我无法更改HTML文件。请在jQuery中为我提供良好的解决方案。预先感谢。
HTML
$('.description').hide();
$('.description:first').show();
$('.expandstory:first').attr('src','/images/minus.png');
$('.expandstory:first').addClass('collapsestory');
$(".expandstory").click(function() {
if($(this).attr('class')=='expandstory') {
$(".description").stop(true,false).slideUp(500); //Here..
$(this).parent().nextAll('.description:first').stop(true,false).slideToggle(500); //Here..
$(this).attr('src','/images/minus.png');
$(this).addClass('collapsestory');
$(this).removeClass('expandstory');
}
else {
$(".description").stop(true,false).slideUp(500); //And here..
$(this).attr('src','/images/plus.png');
$(this).addClass('expandstory');
$(this).removeClass('collapsestory');
}
});
CSS:
<h3><a href="#" title="story title">Story Title</a>
<img class="expandstory" src="/images/plus.png" /></h3>
<div class="description hide">Short description about the story</div>
<h3><a href="#" title="story title">Story Title</a>
<img class="expandstory" src="/images/plus.png" /></h3>
<div class="description hide">Short description about the story</div>
jQuery:
.show
{
display:block;
}
.hide
{
display:none;
}
诸如此类.. $('.expandstory').click(function(){
$(this).parent().next('.description').toggleClass('show hide');
});
http://jsfiddle.net/writetobhuwan/XqauU/
$('h3').next('.description').hide();
$('h3').first().next('.description').show();
$('h3').click(function(){
$(this).find('img').toggleClass('.expandstory');
$('.description').stop().slideUp(500);
$(this).next('.description').stop().slideDown(500);
});
$('img.expandstory').click(function() { var $this = $(this); var $div = $this.parent().next(); $('img.expandstory').not($this).prop('src', '/images/plus.png'); $('div.description').not($div).slideUp(500); $this.prop('src', ( $div.is(':visible') ? '/images/plus.png' : '/images/minus.png' )); $div.slideToggle(); });
注:在小提琴中,我修改了Here's a fiddle的
alt
属性,以便您可以看到它在变化。