点击事件不会触发默认操作
问题描述:
所以,我有这<ol>
与jQuery(1.4.2)的帮助附加一些事件。全部完成在$(document).ready()
-呼叫。点击事件不会触发默认操作
奇怪的是,在<li>
的点击并产生对correnct <a>
点击(我可以通过取消注释console.log()
-part看到这个),但它没有导航UA。为什么是这样? event.stopPropagation()
内部呼叫event.preventDefault()
还是什么?
我知道我可以在<li>
的点击事件中做window.location.href = $('h3 a', this).eq(0).attr('href');
,但我真的很想知道为什么它不适用于点击通话。
在此先感谢同胞!
德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>
(。和是的HTML 4.01已经被验证)
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);
});
答
这是正常的,手动在锚上发射click
确实不是遵循链接,在模拟动作时通常不会发生“默认事件”。设置location.href
是走在这里,像这样的方式:
$('.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
});
顺便说一句,有没有必要为.eq(0)
,.attr('href')
将在匹配集的第一个元素得到href
。
+1,友好提醒 - 这不适用于具有目标属性设置的链接:-) – 2010-09-27 10:16:39
感谢您的澄清尼克。 – anddoutoi 2010-09-27 10:28:04