dssj88098 2013-04-01 03:33
浏览 48
已采纳

jquery触发器在循环中单击

Hi I am trying to append facebook friends thumbnail in list item and add trigger on each of them. but now it trigger the click but it's only getting fbid of the last appended item inside the click callback. How can I attach click event on each of them correctly?

for(var i=0;i<obj.photo.length;i++) {
var img=$('<img src="https://graph.facebook.com/'+obj.photo[i]['fb_id']+'/picture" />');
var anchor=$('<a href="#" id="'+obj.photo[i]['fb_id']+'"></a>');
var li = $('<li></li>');
var fbul = $('#fb_friends');

anchor.append(img);
li.append(anchor);
fbul.append(li);

anchor.click(function(){
    alert(anchor.attr('id'));
});
}
  • 写回答

1条回答 默认 最新

  • doom910730 2013-04-01 03:36
    关注

    the problem is because, you are using a closure variable anchor inside your callback function for click event. The solution to this problem is to fetch the clicked element from the event properties as given below. Inside the event handler method this points to the element to which the handler is registered to.

    anchor.click(function() {
        var $this = $(this);
        alert($this.attr('id'));
    });
    

    But since you are working with dynamic element I recommend using event delegation with .on()

    var fbul = $('#fb_friends');
    
    fbul.on('click', 'a', function() {
        var $this = $(this);
        alert($this.attr('id'));
    })
    
    for (var i = 0; i < obj.photo.length; i++) {
        var img = $('<img src="https://graph.facebook.com/' + obj.photo[i]['fb_id']
                + '/picture" />');
        var anchor = $('<a href="#" id="' + obj.photo[i]['fb_id'] + '"></a>');
        var li = $('<li></li>');
    
        anchor.append(img);
        li.append(anchor);
        fbul.append(li);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献