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.
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
});
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
.
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With