2013-03-21 98 views
1

如何將$(this)對象傳遞給click事件中的函數。嵌套函數調用當前對象

$('#mainwrap img').click(function(){  
    mcImageManager.browse({ 
     oninsert : function(o) { 
      src= o.focusedFile.url; 
      $(this).attr("src", src); 
     } 
    }); 
}); 

任何建議將不勝感激。

+0

你想傳遞$('#mainwrap IMG ')內'oninsert'功能? – Andrew 2013-03-21 09:16:08

回答

4

this是一個特殊的變量 - 每次輸入一個函數,它都會有一個新的值。

在這種情況下,使外部函數的this可在內部功能,您可以將新的變量綁定到它的嵌套函數之外:

$('#mainwrap img').click(function() { 
    var $this = $(this);  // new variable here 
    mcImageManager.browse({ 
     oninsert : function(o) { 
      src= o.focusedFile.url; 
      $this.attr("src", src); // referenced here 
     } 
    }); 
}); 
+0

非常感謝!幫助我擺脫這個難題 – Utsab 2013-03-21 09:30:51