I’m trying to bind some list item links in jquery mobile to a click function with this js
$(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);
});
}
Yes I know that this will only work if the DOM is present on pageInit(). If I try to use the live() function instead every time I click on a list item it fires, but then fires again for how many clicks there have been previously. So the first time I click on a link with class comment_link the click function works but subsequent clicks will make it fire 2x, 3x, etc.
In the docs it says I can use trigger(“create”) on the li item in the listview and then the bind() click function should pick up on those new DOM elements, but I still can’t get it to work this way. http://jquerymobile.com/test/docs/pages/page-scripting.html
The function generating the list views is as follows where data is an array of comments and list is the jquery listview selector.
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");
}
Not sure what I’m doing wrong. Is there a different way to rebind a click event handler?
Try using
delegate()method…..