最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Make an entire <li> element clickable, but don't trigger the link when clicking inside links

programmeradmin3浏览0评论

I've been looking for a solution the last few days, I didn't really found exactly what I'm looking for.

I have something like this:

<ul>
   <li>
      <a href="" class="li-url"></a>
      <h1>Title</h1>
      Lorem ipsum dolor <a href="">Something</a>. Etc, blah blah.
   </li>
</ul>

What I need:

  • Click on the LI element: Go to www.link
  • Click on "Something" inside the LI: Go to www.something (And DON'T go to www.link)

(And I don't know if it's possible, but it would be great if I could click on the LI element and if I'm holding my "alt" key on my keyboard, the link would open in a new tab... like any other link. But I don't know if that's possible)

I've been looking for a solution the last few days, I didn't really found exactly what I'm looking for.

I have something like this:

<ul>
   <li>
      <a href="http://www.link." class="li-url"></a>
      <h1>Title</h1>
      Lorem ipsum dolor <a href="http://www.something.">Something</a>. Etc, blah blah.
   </li>
</ul>

What I need:

  • Click on the LI element: Go to www.link.
  • Click on "Something" inside the LI: Go to www.something. (And DON'T go to www.link.)

(And I don't know if it's possible, but it would be great if I could click on the LI element and if I'm holding my "alt" key on my keyboard, the link would open in a new tab... like any other link. But I don't know if that's possible)

Share Improve this question asked Oct 4, 2010 at 23:32 SantiagoSantiago 2,4656 gold badges31 silver badges43 bronze badges 2
  • You want to have one link inside another link? That would make for a confusing UI, I imagine. And I don't think this is, strictly, possible with CSS (unless you want to wrap each individual element in turn with links). – David Thomas Commented Oct 4, 2010 at 23:41
  • The first link doesn't really show up because it has no text. You could also put the link as an attribute of the LI, but the solution I gave works for the HTML provided. – Gregg Commented Oct 4, 2010 at 23:44
Add a ment  | 

2 Answers 2

Reset to default 4

Here's one way. Tested on jsfiddle and it worked for me.

$('li').click(function() {
    window.location = $(this).find(':first-child').attr('href');
});​​​​​​​​​

As far as the alt key goes, I'm not sure that's possible. I'd let the user decide if they want to open a link in a new tab/window anyway.

You may also be interested in event.stopPropagation(). Which will allow you to prevent the event from bubbling up (aka notifying the li of the click).

$('ul > li').click(function(e) {
    // Go to link.
}).children('a').click(function(e) {
    e.stopPropagation();
    // Go to something.
});

​http://jsfiddle/erF3S/

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论