preventDefault无效<a> inside a <div></div></a>

时间:2012-11-22 10:29:59

标签: jquery preventdefault

我有这个功能:

$(document).ready(function() {

    $('.UIDropDown').click(function () {

        $('.button', this).click(function(e){ e.preventDefault()});

        $(this).addClass('active');


    });

});

以下html:

<div class="UIDropDown">

    <a href="" class="button">button link</a>

    <ul class="submenu">
        <li><a href="">Item</a></li>
        <li><a href="">Item</a></li>
        <li><a href="">Item</a></li>
    </ul>

</div>

为什么e.preventDefault()不能处理.button?页面仍然刷新。

THX,

5 个答案:

答案 0 :(得分:4)

因为在事件实际发生之后绑定了事件处理程序,并且它没有被执行。将事件处理程序绑定到DOM ready事件处理程序中的元素:

$(document).ready(function() {
    // Bind event handler to the button
    $('.UIDropDown .button').click(function(e) { 
        e.preventDefault(); 
    });
    // Bind event handler to the div (click on .button will trigger both)
    $('.UIDropDown').click(function () {
        $(this).addClass('active');
    });
});​

这是working example

答案 1 :(得分:0)

尝试&#34;返回false;&#34;而不是preventDefault();这将阻止转向URI。如:

$('.button', this).click(function(e){ return false; });

答案 2 :(得分:0)

在div点击功能中你不需要链接点击功能。

试试这个吗?

$('.UIDropDown').click(function() {
    $(this).addClass('active');
});

$('.button').click(function(e) {
    e.preventDefault()
});​

答案 3 :(得分:0)

试试这个。

  $('.UIDropDown').click(function () {

    $('.button', this).click(function(e){ return false; });

    $(this).addClass('active');


  });

答案 4 :(得分:0)

你应该写

 $('.button').click(function(e){ e.preventDefault()});

click

$('.UIDropDown')处理程序之外的