【问题标题】:E prevent default not workingE 防止默认不工作
【发布时间】:2013-09-02 09:11:07
【问题描述】:

这是我正在使用的代码:http://jsfiddle.net/qKyNL/12/

$('a').click(function(){
    event.preventDefault();
    var number = $(this).attr('href');
    alert(number);
    // AJAX
    $.ajax({
        url: "/ajax_json_echo/",
        type: "GET",
        dataType: "json",
        timeout: 5000,
        beforeSend: function () {
            // Fadeout the existing content
            $('#content').fadeTo(500, 0.5);
        },
        success: function (data, textStatus) {
            // TO DO: Load in new content
            // Scroll to top
            $('html, body').animate({
                scrollTop: '0px'
            }, 300);
            // TO DO: Change URL
            // TO DO: Set number as active class
        },
        error: function (x, t, m) {
            if (t === "timeout") {
                alert("Request timeout");
            } else {
                alert('Request error');
            }
        },
        complete: function () {
            // Fade in content
            $('#content').fadeTo(500, 1);
        }
    });    
});

我正在尝试使用 Jquery 创建一个可降解的分页,但问题是“e prevent default”似乎没有触发,而是它仍然跟随链接。谁能告诉我如何让这个链接可降解,所以如果 Jquery 被禁用它仍然可以工作。

【问题讨论】:

    标签: javascript jquery ajax graceful-degradation


    【解决方案1】:

    您没有传入事件对象。试试这个:

    $('a').click(function(event){ // <-- notice 'event' passed to handler
    event.preventDefault();
    

    【讨论】:

      【解决方案2】:

      应该是

      $('a').click(function(event){

      在第一行。请注意,event 作为参数传递给匿名函数。

      【讨论】:

        【解决方案3】:

        没有event 传入回调。

        试试

                $('a').click(function(event){
        ------------------------------^
        
                    event.preventDefault();
            }
        

        【讨论】:

          【解决方案4】:

          正如其他答案所说,您需要将事件变量传递给回调

          $('a').click(function(event) {
            event.preventDefault();
          });
          

          您还需要将所有代码包装到就绪函数 jQuery 中,以便仅在 jQuery 准备好处理它们时分配事件侦听器。

          $(document).ready(function() {
              $('a').click(function(event) {
                event.preventDefault();
          
                // the rest of your code
              });
          });
          

          【讨论】:

          • 事实证明这不是必需的。但我觉得这是很好的做法。每个人都有自己的
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-06-29
          • 2012-12-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多