I am newbie for jquery. I have nested li
with same name. And I want to set left position of div
with class open according to clicked li
level. But when I click inside li
it take position of first.
Here is my code
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="open"> <ul> <li class="child"> <a href="#">link1</a> <ul> <li class="child"> <a href="#">menu link1</a> </li> </ul> </li> </ul> </div> <script> $(".child").on("click", function() { var l = $(this).parents('ul').length var a = 101 * l; $(".open").css({ "left": "-" + a + "%" }) }) </script>
Thanks in advance
问题是,当您单击内部li时,单击和单击都发生了,您可以在事件内部使用stopPropagation来防止
you have to disable the bubbling
$(".child").on("click", function(event) {
event.preventDefault(); // diasble default action
event.stopPropagination(); // disable bubbling to parent event
var l = $(this).parents('ul').length
var a = 101*l;
$(".open").css({
"left": "-" + a + "%"
})
})
not tested
You can stopt the propagation with event.stopPropagation();
. I added a console.log()
so that you see what is clicked.
$(".child").on("click", function(event) { event.stopPropagation(); var l = $(this).parents('ul').length var a = 101 * l; console.log("click: " + $(this).find(">a").text()); $(".open").css({ "left": "-" + a + "%" }) })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="open"> <ul> <li class="child"> <a href="#">link1</a> <ul> <li class="child"> <a href="#">menu link1</a> </li> </ul> </li> </ul> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.