我正在努力制作一个可折叠的列表,该列表会从' +'到了' - '和返回取决于列表是折叠还是展开。我可以使用这个声明来看到文本:
$(this).children().eq(i).children('span')[0].firstChild.outerText;
但我无法弄清楚如何改变价值。可能是JQuery Guru可以向我展示的更优雅的解决方案。这是我的JSFiddle。
This answer是我能找到的最接近我的问题的答案,但我不知道如何实施它,或者即使有更好的方法。
答案 0 :(得分:3)
这可以简化很多。而不是尝试匹配索引,只需使用jQuery的find()方法来定位后代:
$('#test > li').click(function() {
var $symbol = $(this).find('.symbol');
$(this).find('ul').slideToggle('fast');
if ($symbol.text() === ' +') {
$symbol.text(' -');
} else {
$symbol.text(' +');
}
});

.hideUnorderedList {
display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<ul id="test">
<li id="first">
<span class="Collapsable"><span class="symbol"> +</span>First One</span>
<ul id="myfirstlist" class="hideUnorderedList">
<li>Something to do</li>
<li>Something else to do</li>
</ul>
</li>
<li id="second">
<span class="Collapsable"><span class="symbol"> +</span>Second One</span>
<ul id="mysecondlist" class="hideUnorderedList">
<li>Second thing to do</li>
<li>Second other thing to do</li>
</ul>
</li>
</ul>
</div>
&#13;
答案 1 :(得分:2)
// Make your code clean and readable!
// Don't target #test. Go directly for your "title/heading" elements ("buttons")
$(".Collapsable").on("click", function() {
// Who is my +/- icon element?
var $ico = $(this).find(".symbol");
// Traverse up to LI and than back down to find my UL sub list:
var $subList = $(this).closest("li").find("> ul");
// Realize the current collapsed/expanded state
var isSubListHidden = $subList.is(":hidden");
// OK, time to rock!
// Change teh text +/-
$ico.text(isSubListHidden ? "-" : "+");
// Toggle sub lists:
$subList.stop().slideToggle();
});
.hideUnorderedList {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<ul id="test">
<li id="first">
<span class="Collapsable"><span class="symbol">+</span>First One</span>
<ul id="myfirstlist" class="hideUnorderedList">
<li>Something to do</li>
<li>Something else to do</li>
</ul>
</li>
<li id="second">
<span class="Collapsable"><span class="symbol">+</span>Second One</span>
<ul id="mysecondlist" class="hideUnorderedList">
<li>Second thing to do</li>
<li>Second other thing to do</li>
</ul>
</li>
</ul>
</div>