2012-04-11 158 views
0

我想知道是否有可能從一個mouseleave函數觸發ajax請求?我希望當鼠標離開li時發送字符串'Y',以便它可以在數據庫中更新。jquery mouseleave ajax請求

這是可能的嗎?

(function(){ 
    $('li#myId').mouseenter(function(){ 
    var y = 'Y'; 
    }).mouseleave(function(){ 

    $.ajax({ 
     type: 'POST', 
     url: 'update.php', 
     data: 'y='+y, 
     success: function(response){ 
     $('li.#myId').html(response); 
     } 

    }); 
    }); 

})();

+0

爲什麼不呢?你只需要在第一次關閉之前移動'var y',因爲它是本地的 – neoascetic 2012-04-11 09:40:10

+1

而且,當然,你的代碼有錯誤。 '$('li。#myId') - > $('li#myId')'甚至是$('li#myId') - > $('#myId')' – neoascetic 2012-04-11 09:41:58

回答

0

當然,只是將y作爲數據存儲。

(function(){ 
    var postY = function (y) { 
     $.ajax({ 
      type: 'POST', 
      url: 'update.php', 
      data: 'y='+y, 
      success: function(response){ 
       $('#myId').html(response); 
      } 
     }); 
    }; 

    // li#myId using both a tag and id is unnecessary since id is unique 
    $('#myId').mouseenter(function(e){ 
     $(this).data('y', 'Y'); 
    }).mouseleave(function(e){ 
     postY($(this).data('y')); 
    }); 
})(); 
0

如果你聲明函數內部的「y」變量,它將只能用於該函數。你應該在你的$(document).ready函數後聲明它,並在事件中改變它。你可以在mouseleave事件觸發時通過ajax發送它。

$(document).ready(function(){ 
    var y = 'Y' 
    $('li#myId').mouseenter(function(){ 
    // whatever you want to do here with "y" 
    }); 

    $('li#myId').mouseleave(function(){ 
    // ajax 
    }); 
}); 
+0

您不應該錯過使用全局這種方式的變量。也分開你的代碼,不要膨脹你的'$(document).ready'函數。 – fredrik 2012-04-11 09:46:05