2014-04-24 39 views
0

我想在某個類中定位某個div,我會使用$(this),但這不起作用,因爲我從另一個函數調用該類。如何定位在ajax內類中被點擊的元素

示例代碼。

$(document).on('click', '.Player', function(e){ 
    var id = $(this).find('.Song_Id').html(); 
    $.ajax({ 
    type:"POST", 
    data: {data:id}, 
    complete: function(){ 
    $(this).attr('src', '../images/appicons/2/16x16/refresh - Red.png') 
    }, 
    url:"php/player/get_song.php" 
    }).done(function(f){ 
     $('#Song_info').html(f) 
    }); 
}) 

從上面,下面是一行我不知道該怎麼impliment。

$(this).attr('src', '../images/appicons/2/16x16/refresh - Red.png'), 

它假定目標類「.player」,但不是整個類,只有被點擊的元素。

謝謝。

回答

1

當執行ajax回調時,默認情況下,回調方法的執行上下文被設置爲ajax設置對象。

您可以使用$.ajax()上下文選項通過自定義執行上下文

$(document).on('click', '.Player', function (e) { 
    var id = $(this).find('.Song_Id').html(); 
    $.ajax({ 
     type: "POST", 
     data: { 
      data: id 
     }, 
     //use context to set the execution context of the callback 
     context: this, 
     complete: function() { 
      $(this).attr('src', '../images/appicons/2/16x16/refresh - Red.png') 
     }, 
     url: "php/player/get_song.php" 
    }).done(function (f) { 
     $('#Song_info').html(f) 
    }); 
}) 

context:

這個對象將作出所有Ajax相關回調的背景下。默認情況下,上下文是表示調用中使用的ajax設置 的對象($ .ajaxSettings與傳遞給 $ .ajax的設置合併)。例如,指定一個DOM元素作爲上下文將 作爲完整回調請求的上下文

2

您可以將$(this)存儲在另一個變量中,並在函數中使用此變量。

$(document).on('click', '.Player', function (e) { 
    var id = $(this).find('.Song_Id').html(), 
     that = $(this); 
    $.ajax({ 
     type: "POST", 
     data: { 
      data: id 
     }, 
     complete: function() { 
      that.attr('src', '../images/appicons/2/16x16/refresh - Red.png') 
     }, 
     url: "php/player/get_song.php" 
    }).done(function (f) { 
     $('#Song_info').html(f) 
    }); 
})