jQuery click event stops working after one click

独自空忆成欢 提交于 2019-12-12 01:23:30

问题


I have a div (#replyLoop) that the link id lmor pulls content into from the href element data-posts when it is clicked. Works fine for the first click, but then after it does nothing. I suspect it has something to do with the structure of the code and not the events used - both "live" and "click" have the same result, as does removing return false; and only using the data-posts element of the link and removing the href portion. (return false; to disable the link's href from firing).

I always seem to miss the most obvious things when it comes to js - and I'm wondering if that's the case here.

(tooltip-e is ensuring that the tipsy function gets called whenever the new content is loaded in. (tooltips))

"Live" markup -

$(function(){
$("#lmor").live("click",function() {
    $('#replyLoop').load($(this).attr('data-posts'), function(data) {
            $('.tooltip-e').tipsy({
            gravity: 'e',
            fade: true,
            html: true
            });
        });
        return false;
    });
});

"Click" markup-

$(function(){
$("#lmor").click(function() {
    $('#replyLoop').load($(this).attr('data-posts'), function(data) {
            $('.tooltip-e').tipsy({
            gravity: 'e',
            fade: true,
            html: true
            });
        });
    return false;
    });
});

Any ideas on what I'm missing?

Edit I figured it out - using a combination of .live and including the "load more" in the appropriate file, I have gotten it to work.

The problem: it was being called outside of the page that was loading - so that when it was looking for a "next" page, that "next" page hadn't been pushed to the link yet because it didn't know it had been loaded.

I have also marked up the live code to use 's instead of "s. Thanks for your help!


回答1:


Would be easier to answer if we wouldn't need to guess, but here is my guess: is #lmor within the html that you load into #replyLoop when it's clicked for the 1st time? I guess it is, and the problem is that $("#lmor").live is set on the DOM element #lmor, then when you load the new content then you delete that dom element and create a new one. The way to do it is:

$(document).on("click", "#lmor", function...);

this way when you create the new #lmor (when loading the new content) it also gets the event listener.

An optimized version could be:

$("#replyLoop").on("click", "#lmor", function...);

if #lmor is inside #replyLoop



来源:https://stackoverflow.com/questions/11074261/jquery-click-event-stops-working-after-one-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!