点击事件仅适用于第一次jquery

时间:2017-05-26 06:24:11

标签: javascript jquery html-framework-7

刷新页面后第一次下面的代码工作。但是,当我再次尝试点击时,它无法正常工作。

点击元素后,它会转到下一页(详细信息页面),当它返回时,点击事件不起作用。

getNewsCategoryloop: function(dataMap){
    var _this = this;
    var text;

    text  = "<div id=\"repeat_get_list_of_category\">";
    for(key in dataMap) {
        text += '<div class="gallery_wrap col-2">\
                    <div class="gallery_view full_image" id="cat'+key+'">\
                        <img src="assets/img/news/athletics_img.jpg" alt="athletics">\
                        <span class="gallery_title">'+ (dataMap[key].field_saf == null ? 'no title' : dataMap[key].field_saf) +'</span>\
                    </div>\
                </div>';
                $(document).on('click', "#cat"+key, function(){
                    _this.getNewsbyCategoryName("#cat"+key);
                })
    }
 text+= "</div>";
 $("#getListOfNewsCategorylist").html(text);            
},  

1 个答案:

答案 0 :(得分:4)

把这段代码: -

$(document).on('click', "#cat"+key, function(){
  _this.getNewsbyCategoryName("#cat"+key);
})

在整个函数本身之外并改变它如下: -

$(document).on('click', ".gallery_view", function(){
  app.getNewsbyCategoryName($(this).attr('id'));
})

所以代码必须是: -

getNewsCategoryloop: function(dataMap){
    var _this = this;
    var text;

    text  = "<div id=\"repeat_get_list_of_category\">";
    for(key in dataMap) {
        text += '<div class="gallery_wrap col-2">\
                    <div class="gallery_view full_image" id="cat'+key+'">\
                        <img src="assets/img/news/athletics_img.jpg" alt="athletics">\
                        <span class="gallery_title">'+ (dataMap[key].field_saf == null ? 'no title' : dataMap[key].field_saf) +'</span>\
                    </div>\
                </div>';

    }
    text+= "</div>";
    $("#getListOfNewsCategorylist").html(text);         
};
$(document).on('click', ".gallery_view", function(){
   app.getNewsbyCategoryName($(this).attr('id'));
})