Reputation: 3823
when i click on my li menu, i need get this link text. The problem is that the menu is a tree and i get a current text with parent text.
For example - when i clik on "test 3" i also get and "test 2". In this situation i need get only "test 3".
I can change only jquery script, html code generate cms.
My code:
<script>
$(document).ready(function(){
$("#menu li").click(function() {
var text = $(this).children('a').text();
alert(text);
});
});
</script>
<div id="menu">
<ul>
<li><a href="#">test 1</a></li>
<li>
<a href="#">test 2</a>
<ul class="sub_menu">
<li><a href="#">test 3</a></li>
<li><a href="#">test 4</a></li>
</ul>
</li>
....
</ul>
</div>
Upvotes: 1
Views: 2171
Reputation: 44900
Use event delegation to use a single listener and listen on the anchors like others suggest:
$(document).ready(function() {
$("#menu").on("click", "a", function(e) {
var text = $(this).text();
alert(text);
// Anchors are navigation, and the default action is to
// load the "href" attribute. Calling 'preventDefault'
// prevents that navigation.
e.preventDefault();
});
});
Upvotes: 0
Reputation: 253496
$("#menu li").click(function(e) {
e.stopPropagation();
var target = e.target,
text = target.textContent || target.innerText;
console.log(text);
});
Upvotes: 1
Reputation: 19086
why not listen on the a
element then?
$(document).ready(function(){
$("#menu a").click(function() {
var text = $(this).text();
alert(text);
});
});
Upvotes: 1