2016-06-21 33 views
1

我試圖通過鏈接點擊提交AJAX功能,我使用的onclick像這樣:的onclick正在訪問的鏈接無論返回false

<a href="<?php echo SITE_URL; ?>watchlist/remove/<?php echo System::escape($this->item->item_id); ?>" onclick="manage_watchlist(); return false;" id="watchlist"> 
    Remove From Watchlist 
</a> 

和我的功能:

var manage_watchlist = function(e) 
{ 
    alert("ff"); 
    e.preventDefault(); 

    $.ajax({ 
     url: $(this).attr('href'), 
     type: 'post', 
     dataType: 'json', 
     success: function(data) 
     { 
      if(data.success) 
      { 
       if($(this).hasClass("remove")) 
       { 
        $(this).text("Add to Watchlist"); 
        $(this).removeClass("remove").addClass("add"); 
        $(this).attr('href', '<?php echo SITE_URL; ?>watchlist/add/<?php echo System::escape($this->item->item_id); ?>'); 
       } 
       else 
       { 
        $(this).text("Remove from Watchlist"); 
        $(this).removeClass("add").addClass("remove"); 
        $(this).attr('href', '<?php echo SITE_URL; ?>watchlist/remove/<?php echo System::escape($this->item->item_id); ?>'); 
       } 
       $('#watch_success_message').html(data.success + alert_close).show(); 
      } 
      else 
      { 
       $('#watch_error_message').html(data.error + alert_close).show(); 
      } 
       <!-- hide loading icon --> 
       $('.ajloading').hide(); 
     }, 
     error: function() 
     { 
      <!-- hide loading icon --> 
      $('.ajloading').hide(); 
     } 
    }); 
    return false; 
} 

我已經在函數中使用了一個警告,所以我的函數正在工作,但由於某種原因它仍然在訪問該鏈接?

+0

你不應該需要兩個'返回FALSE'和'e.preventDefault()'...我只是使用後建議。 – evolutionxbox

+1

''.ajax'內部'this'是'$ .ajax'對象。 –

+0

返回錯誤不會阻止鏈接發射。它將「只」停止傳播(當偵聽器使用jQuery進行設置時它不同,但這不是你在這裏做的)。 –

回答

3

您需要傳入inline事件處理函數。

onclick="manage_watchlist(event);" 

或更好,轉儲內聯事件並使用jQuery附加事件。

0

對於內聯事件e.preventDefault();「阻止」返回false。

只能使用return false;

0

做這樣的事情:

<a href="<?php echo SITE_URL; ?>watchlist/remove/<?php 
echo System::escape($this->item->item_id); ?>" id="watchlist"> 
    Remove From Watchlist 
</a> 

//JS 
$(document).ready(function(){ 
    $('#watchlist').click(function(e){ 
    var $this = $(this); //**this** is the anchor 
    e.preventDefault(); //e is click event. 
    $.ajax({//use $this when you mean the anchor 
     //**this** here is $.ajax 
     //... 
     //your code here 
    });//$.ajax 
    });//$('#watchlist').click 
});//$(document).ready 
0

當你把代碼放到字符串的onclick,你可能認爲它不會採取行動。它的行爲與此類似:

function(event) { 
    manage_watchlist(); 
} 

這就是爲什麼你必須通過事件對象的功能在HTML的onclick。

onclick="manage_watchlist(event);" 

看起來像

function(event) { 
    manage_watchlist(event); 
} 
相關問題