简体   繁体   English

如何防止 jQuery click 事件同时在多个元素上触发?

[英]How to prevent jQuery click event firing on multiple elements at same time?

I have the above code which ideally will slide toggle the ulContainer but it doesn't work as expected.我有上面的代码,理想情况下可以滑动切换ulContainer但它没有按预期工作。 I would like it so when I click on the selector above, it only toggles one of the ul#dropdown-download-links li > a one click at a time.我希望如此,当我单击上面的选择器时,它只会切换ul#dropdown-download-links li > a一次单击之一。 Currently, obviously it toggles them all on click.目前,显然它会在点击时全部切换。

 $(document).ready(function() { $("ul#dropdown-download-links li > a").unbind().click(function(e) { var ulContainer = $(this).closest("li"); e.preventDefault(); $(ulContainer).slideToggle(); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul id="dropdown-download-links"> <li><a href="#">Test</a> <ul> <li><a href="#">Toggle on click etc</a></li> </ul> </li> <li><a href="#">Test</a> <ul> <li><a href="#">But don't toggle on click of first one</a></li> </ul> </li> </ul>

I hope that makes sense, I feel like it's a super common probelm it's just hard to explain.我希望这是有道理的,我觉得这是一个超级常见的问题,很难解释。

The event is bound on the 'a' element, to get and toggle the child items, you first need to go up one level with the 'parent()' method which returns the 'li' element.该事件绑定在 'a' 元素上,要获取和切换子项,您首先需要使用返回 'li' 元素的 'parent()' 方法上升一级。 After that use the find method to get the child list items.之后使用 find 方法获取子列表项。

 $(document).ready(function(){ $("ul#dropdown-download-links li > a").unbind().click(function(e) { var ulContainer = $(this).parent().find("li"); e.preventDefault(); $(ulContainer).slideToggle(); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul id="dropdown-download-links"> <li><a href="#">Test</a> <ul> <li><a href="#">Toggle on click etc</a></li> <li><a href="#">Toggle on click etc</a></li> </ul> </li> <li><a href="#">Test</a> <ul> <li><a href="#">But don't toggle on click of first one</a></li> </ul> </li> </ul>

 $(document).ready(function(){ $("ul#dropdown-download-links li:first-child >a").unbind().click(function(e) { var ulContainer = $(this).closest("li"); e.preventDefault(); $(ulContainer).slideToggle(); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul id="dropdown-download-links"> <li><a href="#">Test</a> <ul> <li><a href="#">Toggle on click etc</a></li> </ul> </li> <li><a href="#">Test</a> <ul> <li><a href="#">But don't toggle on click of first one</a></li> </ul> </li> </ul>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM