每个李后都有手风琴

时间:2017-11-22 01:28:40

标签: jquery html css accordion

所以昨天我问了一个问题:Applying Accordion with div having data-attribute as title

但是我发现这不是使用data-attr的理想方法,因为当我想用它来切换时,我不能将它用作jQuery中的选择器。

我有一个这样的结构......在div之前显示标题。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li id="first">1st Title</li>
  <li id="second">2nd Title</li>
  <li id="third">3rd Title</li>
  <li id="fourth">4th Title</li>
</ul>
<div id="first_div">First content <br/>1111111111111111111111</div>
<div id="second_div">Second content <br/>22222222222222222222</div>
<div id="third_div">Third content <br/>33333333333333333333</div>
<div id="fourth_div">Fourth content <br/>4444444444444444444</div>
1st Title

2nd Title

3rd Title

4th Title

我想让它像

1st Title

First Content

2nd Title

3rd Title

4th Title

- &GT;点击“第一个标题”,它变为

a = array([1, 0, 1, 1, 0, 1])

b = array([0, 1, 1, 1, 0, 0])

点击其他标题时类似 不改变html结构(ul li first first和div after)

任何人都可以为我提供一些解决方案,因为我已经挣扎了好几天...想知道如何解决它!谢谢!

1 个答案:

答案 0 :(得分:1)

这是你想要达到的目标吗?

$("li").on("click", function(e) {
  
  $("li").not(this).removeClass("has-content");
	$("li").not(this).find(".extra").remove();
  
  // console.log("ID", $(this).attr("id"));
  var div_id = "#" + $(this).attr("id") + "_div";
  
  var div_content = $(div_id).html();
  // console.log(div_content);
  if (!$(this).hasClass("has-content")) {
    $(this)
      .addClass("has-content")
      .append("<div class='extra'>" + div_content + "</div>");  
  }
  else {
  	$(this).removeClass("has-content");
		$(this).find(".extra").remove();
  }
  
});
ul {
  margin: 0;
  padding: 0;
}

li {
  list-style: none;
  padding: 10px 0;
  background: #ff0;
}

div {
  background: lightgray;
  display: none;
}

div.extra {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li id="first">1st Title</li>
  <li id="second">2nd Title</li>
  <li id="third">3rd Title</li>
  <li id="fourth">4th Title</li>
</ul>
<div id="first_div">First content <br/>1111111111111111111111</div>
<div id="second_div">Second content <br/>22222222222222222222</div>
<div id="third_div">Third content <br/>33333333333333333333</div>
<div id="fourth_div">Fourth content <br/>4444444444444444444</div>