for循环后访问元素的id

时间:2013-04-22 11:53:08

标签: jquery for-loop onclick

我正在使用.get()来建立一个季节列表。当我执行此操作时,我会将<li><a>附加到<ul>元素。在加载之后,我想访问<a>元素以返回它们的ID,onclick。但是,当我尝试这个时,我无法访问这些元素。

<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>

3 个答案:

答案 0 :(得分:1)

尝试使用.on -

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

答案 1 :(得分:0)

使用.on()将事件处理程序附加到父元素,并将选择器作为参数传递。这适用于动态添加的元素......

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

答案 2 :(得分:0)

您需要使用委托来动态添加元素:

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

检查documentation