2010-11-16 106 views
0

在下面的代碼中的問題,我需要得到已引發事件與jQuery的獲取元素的ID

$(document).ready(function() 
{ 
    $(".selectors").live('change', function() 
    { 
     $.post("GetCategoriesByParentId/", { ID: $(this).val() }, function (data) 
     { 
      var idd = $(this).attr('id'); //here 
     }); 
    }); 
}); 

元素的ID,但idd總是「未定義」。爲什麼?

+0

更改事件綁定到的HTML將會很有用。 – 2010-11-16 19:22:01

+1

在該上下文/作用域中,這不是後對象嗎? – wajiw 2010-11-16 19:22:09

回答

3

$.post回調的上下文中,this的值將設置爲與live呼叫的值不同。你需要緩存的this值:

$(document).ready(function() 
{ 
    $(".selectors").live('change', function() 
    { 
     var idd = this.id; 

     $.post("GetCategoriesByParentId/", { ID: $(this).val() }, function (data) 
     { 
      // idd is now the id of the changed element 
     }); 
    }); 
}); 
1

$(this).post函數內部實際上不是你父迭代循環通過集合當前元素。修復:

$(".selectors").live('change', function() 
{ 
    $thisElement = $(this); 

    $.post("GetCategoriesByParentId/", { ID: $(this).val() }, function (data) 
    { 
     var idd = $thisElement.attr('id'); //here 
    }); 
});