0

I'm making an menu and for that I use jquery to display data.

I want to make it more dynamic and for that I'm using the each() function

Here is an representative example of my code http://jsfiddle.net/4r5cLy00/

As you can see the on click displays all the listitems of the unordered list and that's not want i want. I want to get the clicked <li>

I hope someone have a simple solution for this?

2 Answers 2

2

Do you mean like this?

$(document).ready(function() {
    $('ul > li').click(function() {
        alert($(this).text());
    });
});

http://jsfiddle.net/4r5cLy00/1/

Sign up to request clarification or add additional context in comments.

5 Comments

exactly! Why do you use the operator instead of space?
sorry, which operator do you mean? Is it the > (greater than) symbol? That just means the li's that are direct descendants of the the ul. It could be written as $('ul li') and still work fine but it would work for any child li's aswell which you may or may not want. It's also useful in CSS if you only want to style top level li's for example.
A space would just be a descendant selector. The > denotes a child selector. It's just a way to give more specificity. css-tricks.com/child-and-sibling-selectors
The only thing I don't like about this solution is that it doesn't use event delegation. You can do this with one event bound the the <ul> instead of x number of list items.
Thanks @jeff and for your replies and explanation!
0

This is how you'd use event delegation in this instance. It's a good practice and every JS programmer should use it. The advantages are that you only bind one event and you get better performance. Read more here:

http://bdadam.com/blog/plain-javascript-event-delegation.html

$('ul').click(function(event) {
  if (event.target.tagName == 'LI') {
    console.log(event.target.innerText);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
</ul>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.