代码之家  ›  专栏  ›  技术社区  ›  anddoutoi

单击事件不会触发默认操作

  •  1
  • anddoutoi  · 技术社区  · 15 年前

    所以,我有这个 <ol> 在jQuery(1.4.2)的帮助下附带了一些事件。一切尽在掌握之中 $(document).ready() -打电话。

    <li> 是否生成相应的单击 <a> (我可以通过取消注释 console.log() -部分),但它不导航UA。为什么会这样?做 event.stopPropagation() 呼叫 event.preventDefault()

    window.location.href = $('h3 a', this).eq(0).attr('href'); <

    代码:

    <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);
    });
    
    1 回复  |  直到 15 年前
        1
  •  2
  •   Nick Craver    15 年前

    这是正常的,手动启动 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