0

我正在使用 .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>
4

3 回答 3

1

尝试使用.on-

 $(document).on('click',"#seasonlist > li > a",function(){
     var test = $(this).attr("id");
     console.log(test);
 });
于 2013-04-22T11:56:44.100 回答
0

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

 $("#seasonlist").on('click', 'li > a', function(){
      var test = $(this).attr("id");
      console.log(test);
 });
于 2013-04-22T11:56:16.423 回答
0

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

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

检查文档

于 2013-04-22T11:56:16.323 回答