[英]Toggle childrens when parent li is clicked
I'm trying to make a tree like structure wich branches can be shown/colapsed when parent is clicked. 我正在尝试制作树状结构,当点击父母时,可以显示/折叠分支。 Wathever I tried so far, it seems that I can't prevent the whole tree to colapse whenever any item from the tree is clicked, leaving only the root element.
Wathever我到目前为止尝试过,似乎无法阻止整棵树在点击树中的任何项目时崩溃,只留下根元素。 I tried with children, Parent, sibling, having a class to the root ul, to all the ul, on li, using unique Id instead of class ... Nothing worked for me.
我尝试过孩子,父母,兄弟姐妹,有一个基础ul的课程,所有的ul,li,使用唯一的Id而不是课程...没有什么对我有用。 Always this weird behaviour, errors, or nothing.
总是这种奇怪的行为,错误或什么都没有。
view: 视图:
<script type="text/javascript">
$(document).ready(function() {
$('.tree').click(function () {
$(this).find('ul').slideToggle();
});
});
</script>
<h2>testArbre</h2>
<ul>
<li class="tree">
@Model.Name
@ShowTree(@Model)
</li>
</ul>
@helper ShowTree(Tree tree)
{
<ul>
@foreach (var branch in tree.Branch)
{
<li class="tree">
@branch.Name
@if (branch.Branches.Any())
{
@ShowTree(branch)
}
</li>
}
</ul>
}
Model: 模型:
public class ArbreDroits
{
public string Name { get; set; }
public List<Tree> Branches { get; set; }
public Tree(string name)
{
Name = name;
Branches = new List<Tree>();
}
public ArbreDroits AddBranch(string name)
{
Branches.Add(new Tree(name));
return Branches.Last();
}
}
the generated html looks like this: 生成的HTML看起来像这样:
<ul>
<li class="tree">
racine
<ul>
<li class="tree">
noeud1
<ul>
<li class="tree">
noeud1Fils1
</li>
<li class="tree">
noeud1Fils2
<ul>
<li class="tree">
noeud1Fils2Fils1
<ul>
<li class="tree">
noeud1Fils2Fils1Fils1
</li>
</ul>
</li>
</ul>
</li>
<li class="tree">
noeud1Fils3
</li>
</ul>
</li>
<li class="tree">
noeud2
</li>
</ul>
</li>
</ul>
My bet is you need to stop click event propagation and only target direct descendant using children()
: 我敢打赌,你需要停止点击事件传播,并且只使用
children()
定位直接后代:
$(document).ready(function() {
$('.tree').click(function(e) {
e.stopPropagation();
$(this).children('ul').slideToggle();
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.