2

Due some weirdness I'm stuck with using javascript to Jquery to get a link to work by clicking the a parent li element. Basically clicking anywhere on the li should take the user to the link of the a that is a direct child of it. What I have some far does not seem to work. The code:

<ul>
<li onclick="location.href='$(this).children('a:first').attr('href')';">
    <a href="http://example.com/">link</a>
    </li>
    </ul> 

Thank you!

Stephan Muller
  • 27,018
  • 16
  • 85
  • 126
Epleroma
  • 153
  • 6
  • 15

3 Answers3

7

You could simplify your code by moving not using onclick, but rather using a selector to target that node and have a click event there.

$(".myUl li").on("click", function() {
    location.href = $(this).children("a").attr("href");
});

But you really should solve this by using css. You can use display: block; on the <a> as well, and have that fill the content, add extra paddings and basically behave like a div but keep the linking capability.

Zenorbi
  • 2,504
  • 2
  • 15
  • 18
  • Yeah I know this should be a css solution, but the actual page in question has some php that somehow is restricting the links from working normally, so as I'm unable to decipher it, I tried to use JS instead. – Epleroma Sep 26 '14 at 19:44
4

When you put single quotes around the href, its seen as a string. Also, you used single quotes within other single quotes, which ends the string prematurely. It literally tries to go to the url "$(this).children(".

Instead, remove the single quotes around the location.href

<ul>
    <li onclick="location.href=$(this).children('a:first').attr('href');">
        <a href="http://example.com/">link</a>
    </li>
</ul> 

Also, you really shouldn't use inline scripts like this. It's much better to add a script tag to the bottom of the page and put a script in there that binds to the li's click event.

Stephan Muller
  • 27,018
  • 16
  • 85
  • 126
1

replace with this

    <li onclick="location.href=$(this).children('a:first').attr('href');">
mondersky
  • 441
  • 2
  • 15