问题
I got a structure like this... to display the title before the div with data-attribute.
I want to make it like
1st Title
2nd Title
3rd Title
4th Title
-> Click "1st Title", it becomes
1st Title
First Content
2nd Title
3rd Title
4th Title
So I want to ask is there any ways that I can apply this accordion on it without changing the html structure (Having ul,li first then show the div)?
ul {
display:none;
}
div:before {
content:attr(data-title);
display:block;
font-size:14px;
background:gray;
text-align:center;
line-height:14px
}
div {
background:lightgray;
}
<ul>
<li id="first">1st Header</li>
<li id="second">2nd Header</li>
<li id="third">3rd Header</li>
<li id="fourth">4th header</li>
</ul>
<div id="first_div" data-title="1st Header title">First content <br/>1111111111111111111111</div>
<div id="second_div" data-title="2nd Header title">Second content <br/>22222222222222222222</div>
<div id="third_div" data-title="3rd Header title">Third content <br/>33333333333333333333</div>
<div id="fourth_div" data-title="4th Header title">Fourth content <br/>4444444444444444444</div>
回答1:
Here you go with a solution
$('li').click(function(){
if($(this).find('div.content').length == 0){
$(this).append('<div class="content">' + $('#' + $(this).attr('id') + '_div').html() + '</div>');
$('li').each(function(){
if($(this).find('div.content').length != 0)
$(this).find('div.content').slideUp();
});
$(this).find('div.content').slideDown();
} else {
if($(this).find('div.content').css('display') == 'block'){
$(this).find('div.content').slideUp();
} else {
$(this).find('div.content').slideDown();
}
}
});
li {
list-style: none;
}
div:before {
content:attr(data-title);
display:block;
font-size:14px;
background:gray;
text-align:center;
line-height:14px
}
div {
background:lightgray;
}
.content{
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li id="first">1st Header</li>
<li id="second">2nd Header</li>
<li id="third">3rd Header</li>
<li id="fourth">4th header</li>
</ul>
<div class="content" id="first_div" data-title="1st Header title">First content <br/>1111111111111111111111</div>
<div class="content" id="second_div" data-title="2nd Header title">Second content <br/>22222222222222222222</div>
<div class="content" id="third_div" data-title="3rd Header title">Third content <br/>33333333333333333333</div>
<div class="content" id="fourth_div" data-title="4th Header title">Fourth content <br/>4444444444444444444</div>
Hope this will help you.
来源:https://stackoverflow.com/questions/47404940/applying-accordion-with-div-having-data-attribute-as-title