0

我有一个链接列表,每个链接都有 href 属性:

<a href="./page1.php" class="points">page 1</a>
<a href="./page2.php" class="points">page 2</a>
<a href="./page3.php" class="points">page 3</a>
<a href="./page4.php" class="points">page 4</a>

我有一个“点”类的听众:

$(".points").live('click',function(){
    id = $(this).attr("id");
    $.ajax({
        type: "POST",
        url: 'points.php',
        data:{id:id},
        success: function()
        {

        },
        error : function(XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
            alert(textStatus);
            alert(errorThrown);
            alert(XMLHttpRequest.responseText);
        }
    });
});

href 有效,但点击无效,当我删除 href 属性时,点击监听器工作正常。这两个可以一起工作吗?

4

3 回答 3

2

您需要取消默认行为,因为您一离开,脚本就会停止运行。您可以考虑等到 Ajax 调用完成,然后通过脚本导航:

$(".points").live('click',function(e){ // <--- Add e parameter

    e.preventDefault(); // <--- Add this

    id = $(this).attr("id");
    href = $(this).attr("href"); // Link we will navigate to when done
    $.ajax({
        type: "POST",
        url: 'points.php',
        data:{id:id},
        success: function()
        {
           location.href = href; // Do the navigation now that we're done
        },
        error : function(XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
            alert(textStatus);
            alert(errorThrown);
            alert(XMLHttpRequest.responseText);
        }
    });
});
于 2013-10-16T19:58:20.153 回答
2

试试这个:

$(".points").live('click',function(e){ //added e as function argument
    e.preventDefault(); //added preventDefault();
    var id = this.id; // changed here to this.id, and added var (so it will be a local variable)
    $.ajax({
        type: "POST",
        url: 'points.php',
        data:{id:id},
        success: function()
        {

        },
        error : function(XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
            alert(textStatus);
            alert(errorThrown);
            alert(XMLHttpRequest.responseText);
        }
    });
});
  • 阅读有关preventDefault()
  • 注意As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.
于 2013-10-16T19:58:43.937 回答
0

让 Ajax 和 Href 一起工作

尝试

  $(".points").live('click',function(e){
  e.preventDefault();
  var id = $(this).attr("id");
  var url= $(this).attr("href");

   $.ajax({
   type: "POST",
   url: 'points.php',
   data:{id:id},
    success: function()
    {
     //Do something before going to page
       window.location.href=url;

    },
    error : function(XMLHttpRequest, textStatus, errorThrown) {
        alert(XMLHttpRequest);
        alert(textStatus);
        alert(errorThrown);
        alert(XMLHttpRequest.responseText);
    }
   });
   });
于 2013-10-16T20:06:56.330 回答