【问题标题】:preventDefault not working on <a> inside a <div>preventDefault 在 <div> 内的 <a> 上不起作用
【发布时间】:2012-11-22 18:43:07
【问题描述】:

我有这个功能:

$(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 上不起作用?页面仍在刷新。

谢谢,

【问题讨论】:

标签: jquery preventdefault


【解决方案1】:

因为您绑定了事件处理程序之后,该事件实际上已经发生,并且它没有被执行。将事件处理程序绑定到 DOM 就绪事件处理程序中的元素:

$(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

【讨论】:

    【解决方案2】:

    尝试“返回错误;”而不是 preventDefault();这将阻止转到 URI。如:

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

    【讨论】:

    • 如果事件绑定发生在正确的位置,preventDefault 将正常工作。看我的回答。
    【解决方案3】:

    在 div 点击函数中你不需要那个链接点击函数。

    试试这个?

    $('.UIDropDown').click(function() {
        $(this).addClass('active');
    });
    
    $('.button').click(function(e) {
        e.preventDefault()
    });​
    

    【讨论】:

      【解决方案4】:

      试试这个。

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

      【讨论】:

      • 这不会有任何区别。如果事件绑定发生在正确的位置,preventDefault 将正常工作。看我的回答。
      【解决方案5】:

      你应该写

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

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

      【讨论】:

      • 当您将.button 事件绑定移到其他事件处理程序之外时,您可能不想要this 上下文参数。
      猜你喜欢
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      • 2013-12-22
      • 1970-01-01
      • 2012-12-18
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      相关资源
      最近更新 更多