问题
I have the following structure.
<ul id="browser" class="filetree">
<li><span class="folder">Folder 1</span>
<ul>
<li><span class="file">Item 1.1</span></li>
</ul>
</li>
<li><span class="folder">Folder 2</span>
<ul>
<li><span class="folder">Subfolder 2.1</span>
<ul id="folder21">
<li><span class="file">File 2.1.1</span></li>
<li><span class="file">File 2.1.2</span></li>
</ul>
</li>
<li><span class="file">File 2.2</span></li>
</ul>
</li>
<li class="closed"><span class="folder">Folder 3 (closed at start)</span>
<ul>
<li><span class="file">File 3.1</span></li>
</ul>
</li>
<li><span class="file">File 4</span></li>
</ul>
In js I have the following function.
$("#browser li").click(function(){
});
When I clicked on li File 2.1.1. The function calls 3 times
first time for li File 2.1.1 , second time for li Subfolder 2.1 and third time for li Folder 2.
Can anyone give me the solution to call the function exactly once?
Your Help is greatly Appriciated. Thanks.
回答1:
That is because you have many li
elements under #broswer
.
Try this instead:
$("#browser>li").click(function(){
//only direct children of #browser
//your code
});
Or you can use event.stopPropagation():
$("#browser li").click(function(event){
event.stopPropagation();
//your code
});
回答2:
Change your function to
$("#browser li").click(function(event){
event.stopPropagation();
//do your other stuff
});
That way, the click on the lower-level li
won't "bubble up" to the higher level li
.
回答3:
This is due to the fact events "bubble" up your dom so you if you click
File 2.1.1, it will also be heard by File 2.1 and File 2 to fix this change event to
$("#browser li").click(function(e){
//Your code here
e.stopPropagation();
});
回答4:
Rather than use the click event on the li object add another element (in example span) and handle click in that. This way can still bubble for higher events just doesn't bubble through nested li.
//Run the following to see the no li bubble result
$(".nobubble").on('click',function(){
$("#result").append($(this).attr("data-id") +"<br />")
});
//uncomment the following to see the li bubble result
/*$(".bubble").on('click',function(){
$("#result").append($(this).attr("data-id") +"<br />")
});*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="bubble" data-id="li-a"><span class="nobubble" data-id="span-a">a</span>
<ul>
<li class="bubble" data-id="li-b"><span class="nobubble" data-id="span-b">b</span>
</li>
</ul>
</li>
</ul>
<div id="result">
</div>
来源:https://stackoverflow.com/questions/11123829/jquery-nested-li-click-event-calls-multiple-times