gpt4 book ai didi

Jquery 多个点击事件中的每个函数

转载 作者:行者123 更新时间:2023-12-01 08:26:10 24 4
gpt4 key购买 nike

单击时,我希望打开此特定的 .parents ul,并折叠所有其他 .parents ul。下面的代码对我不起作用。

我想我不明白如何在下面的代码中使用 this 和误用 e

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="/der/jquery.cookie.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var selected;
$(".parents").click(function(){
selected = this.id;

// Open list
$("#" + selected + " ul").css("display", "block");

// Remember opened list
$.cookie('tree', '#' + this.id);

// Cycle through all lists
$(".parents").each(function(e){
// Collapse all children that does not
// belongs to the opened list
if(e.id != selected) {
$("#" + e.id + " ul").css("display", "none");
}
});
});
});
</script>
<style type="text/css">
.child_list {
display: none;
}
</style>
</head>
<body>
<ul id="tree">
<li class="parents" id="parent_1"><a href="#">Parent 1</a>
<ul class="child_list">
<li class="child"><a href="#">Child 1</a>
<li class="child"><a href="#">Child 2</a>
<li class="child"><a href="#">Child 3</a>
</ul>
</li>
<li class="parents" id="parent_2"><a href="#">Parent 2</a>
<ul class="child_list">
<li class="child"><a href="#">Child 1</a>
<li class="child"><a href="#">Child 2</a>
<li class="child"><a href="#">Child 3</a>
</ul>
</li>
</ul>
</body>
</html>

最佳答案

不要重新选择事物,而是相对于 this 查找它们,您点击的项目,如下所示:

$(function(){
$(".parents").click(function(){
// Open list
$(this).find("ul").show();

// Remember opened list
$.cookie('tree', '#' + this.id);

// Cycle through all lists
$(this).siblings().find("ul").hide();
});
});​

You can give it a try here (除了 cookie 之外的所有内容)。您还可以使用 .slideUp() 为其添加一些动画。和 .slideDown() 而不是 .hide() .show() , check that option here .

上述方法使用tree traversal ,所以你从 <li> 开始您单击,然后四处移动以找到您想要的内容,例如其他 .siblings() 关闭他们的 child 等。

关于Jquery 多个点击事件中的每个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3666370/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com