2013-04-22 107 views
0

我正在使用.get()構建季節列表。當我這樣做時,我將<li><a>附加到我的<ul>元素上。加載完成後,我想訪問<a>元素以返回其ID,點擊。但是,當我嘗試這個時,我無法訪問這些元素onclick。循環後訪問元素的ID

<script type="text/javascript"> 
    $(function(){ 
     var org = localStorage.getItem("org"); 
     var key = localStorage.getItem("key"); 
     var user = localStorage.getItem("user"); 
     $.get('https://domain.com/App/GetSeasons/?user='+user+'&key='+key+'&org='+org, function(xml){ 
      var seasons = $.xml2json(xml); 
      for (i=0; i<=seasons.Season.length; i++){ 
      var seasonName = seasons.Season[i].name; 
      var SeasonID = seasons.Season[i].id; 
      $("#seasonlist").append("<li><a href='#' id="+SeasonID+">" + seasonName + "<span class=pull-right>></span></a></li>"); 
      } 
      }); 
     }); 
    </script> 
<script> 
     $("#seasonlist > li > a").click(function(){ 
          var test = $(this).attr("id"); 
             console.log(test); 
             }); 
</script> 

回答

0

您需要使用委派動態添加元素:

$('#seasonlist').on("click", 'li > a', function() { 
    var test = $(this).attr("id"); 
    console.log(test); 
}); 

檢查documentation

0

使用.on()將事件處理程序附加到父元素,並將選擇器作爲參數傳遞。這適用於動態地添加的元素,以及...

$("#seasonlist").on('click', 'li > a', function(){ 
     var test = $(this).attr("id"); 
     console.log(test); 
}); 
1

嘗試使用.on -

$(document).on('click',"#seasonlist > li > a",function(){ 
    var test = $(this).attr("id"); 
    console.log(test); 
});