【问题标题】:jquery mobile live() fires too many times bind() wont fire after DOM injectionjquery mobile live() 触发次数过多 bind() 在 DOM 注入后不会触发
【发布时间】:2012-03-30 12:02:08
【问题描述】:

我正在尝试使用此 js 将 jquery mobile 中的一些列表项链接绑定到单击功能

$(document).bind('pageinit', function(event){

   $('a.comment_link').bind("click",function() {

    var comment_id = $(this).attr('comment_id');
    window.localStorage.setItem("comment_id",comment_id);

});

}

是的,我知道这只有在 pageInit() 上存在 DOM 时才有效。如果我每次单击列表项时都尝试使用 live() 函数,它会触发,但随后会再次触发之前的点击次数。因此,当我第一次单击带有类 comment_link 的链接时,单击功能有效,但随后的单击将使其触发 2x、3x 等。

在文档中,它说我可以在列表视图中的 li 项目上使用 trigger("create"),然后 bind() click 函数应该获取那些新的 DOM 元素,但我仍然无法得到它以这种方式工作。 http://jquerymobile.com/test/docs/pages/page-scripting.html

生成列表视图的函数如下,其中data是一个cmets数组,list是jquery listview选择器。

function generateComments(data,list){

list.html("");

$.each(data, function(key, comment) {
    var img;

    if(comment.user.icon){
        img = '<div class="icon_wrapper"><img src="http://stage.domain.com/assets/img/user/'+comment.user.icon+'"/></div>';
    }
    else{
        img = '';
    }

    var prettyTime = humaneDate(comment.created_at)

    var item = '<li class="blank"><a href="userprofile.html" class="comment_link" type="'+data.type+'" user_id="'+comment.user.user_id+'" id="'+comment.id+'">'+img+'<h4>'+comment.user.name+'</h4><p>'+comment.data+'</p><div class="stamp_wrapper"><p class="ui-li-aside">'+prettyTime+'</p></div></a></li>';

    list.append(item).trigger('create');
});

list.listview("refresh");

}

不知道我做错了什么。是否有其他方法可以重新绑定单击事件处理程序?

【问题讨论】:

    标签: jquery jquery-mobile


    【解决方案1】:

    尝试使用delegate()方法.....

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多