Reputation: 37
I found a lot of questions about this, but I have problem with getting the single id of a nested li
element, and I couldn't find answer for it. Here is my code:
$(function() {
$('ul').on('contextmenu', 'li', function(e) {
e.preventDefault();
console.log(this.id);
});
And here is my HTML:
<ul id="u-main-ul">
<li id="1"> 1
<ul id="u-1">
<li id="11">11</li>
</ul>
</li>
</ul>
The problem is that when I right click on the li
element with id="11"
, on the console it writes "1 11". When click one li
element it shows and the id of all others li
tags that are placed before the clicked one.
I want to get the id only of the right-clicked li
tag and nothing else.
Upvotes: 0
Views: 288
Reputation: 35338
Try it with stopPropagation() like so
$(function() {
$('ul').on('contextmenu', 'li', function(e) {
e.stopPropagation();
console.log(this.id);
})
});
See the JSFiddle
Upvotes: 1
Reputation: 36642
You need to stop the event from bubbling up the tree:
$('ul').on('contextmenu', 'li', function(e) {
e.preventDefault();
e.stopPropagation();
console.log(this.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="u-main-ul">
<li id="1">1
<ul id="u-1">
<li id="11">11</li>
</ul>
</li>
</ul>
See the documentation for more info.
Upvotes: 3