Skip to content
Advertisement

Have multiple links in an ul but only first link is used on click event

I want the user to be able to choose between two links, however, whichever line they select it always runs the first ‘href’.

JavaScript

This is my jQuery code. I assume that it stops running once it finds the first href but I am curious how I can prevent that and allow it to select the second if clicked.

JavaScript

Advertisement

Answer

Problem:

Well it’s obvious that your code always uses the first link href because of your following code:

JavaScript

You are attching click to the ul and then you are writing $(this).find('a') so when it finds a matching link(which is the first), it will proceed with it.

Solution:

You need to change your code to attach the click event to li elements or directly to <a> elements, so change your code to:

JavaScript

This way when you call $(this).find('a'), it will only fetch inside the clicked li element, so it will get the right link.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement