Click event does not fire default action
So, I have this <ol>
with some events attached with the help of jQuery (1.4.2). All is done in the $(document).ready()
-call.
The weird thing is that the click on the <li>
does generate a click on the correnct <a>
(I can see this by uncommenting the console.log()
-part) but it does not navigate the UA. Why is this? Does event.stopPropagation()
call event.preventDefault()
internally or what?
I know I can do window.location.href = $('h3 a', this).eq(0).attr('href');
in the click event of the <li>
but I really would like to know why it´s not working with the click-call.
Thanks in advance fellow SOers!
Teh codez:
HTML:
<ol class="news">
<li>
<img src="http://dummyimage.com/325x325/000/fff.jpg">
<span class="date">12th of May</span>
<h3><a href="http://example.com/lorem-ipsum">Lorem Ipsum</a></h3>
<p>Nullam rhoncus, massa nec posuere rutrum, mauris metus ornare lacus, facilisis. Rhoncus purus dui vel lectus.</p>
</li>
<li>
<span 开发者_如何学编程class="date">3rd of May</span>
<h3><a href="http://example.com/lam-sum-idum">Lam sum idum</a></h3>
<p>Mauris volutpat enim nec turpis pharetra consectetur. Cras faucibus mattis dignissim.</p>
</li>
<!-- many more LIs here... -->
</ol>
(and yes. The HTML 4.01 has been validated.)
JavaScript:
$('.news li').click(function () {
$('h3 a', this).eq(0).click();
}).hover(function () {
$(this).toggleClass('hover');
}).find('h3 a').click(function (e) {
e.stopPropagation();// prevent recursion
//console.log(this);
});
This is normal, manually firing a click
on an anchor does not follow the link, firing the "default event" is often not the case when simulating the action. Setting the location.href
is the way to go here, like this:
$('.news li').click(function () {
window.location.href = $(this).find('h3 a').attr('href');
}).hover(function () {
$(this).toggleClass('hover');
}).find('h3 a').click(function (e) {
e.stopPropagation(); //so ctrl+click works on the link, etc
});
As an aside, there's no need for the .eq(0)
, .attr('href')
will get the href
from the first element in the matched set.
精彩评论