jQuery script works only once

2019-09-17 11:32发布

问题:

I have little problem, script works only once, after that I need to refresh page to remove favorite article (script is for that).

$("a.fav_no").on('click', function () {
            var id = $(this).attr("id");
            $(this).load("{$homepage}/user_action.php?action=fav&id="+ id +"").addClass("fav_yes");
        });

$("a.fav_yes").on('click', function () {
            var id = $(this).attr("id");
            $(this).load("{$homepage}/user_action.php?action=remove_fav&id="+ id +"").removeClass("fav_yes");
        });

In console, I get id of article (div) on click after many times on click (so it count) but it doesn't do anything. So I can right now just favorite, to remove from favorites I need to refresh then to click again on link to remove from favorites.

Thanks!

回答1:

If you use the .on() overload that takes 3 args and is called on the document. Then the events will remain hooked up as UI elements come and go. No need to re add them every time.

$(document).on("click", "a.offsite", function(){ .....

See the description of .on() here. http://api.jquery.com/live/



回答2:

If you are replacing the html that is responsible for catching the events, you should init those event catchers again.

like this:

initEvents() {
     $("a.fav_no").on('click', function () {
        var id = $(this).attr("id");
        $(this).load("{$homepage}/user_action.php?action=fav&id="+ id +"").addClass("fav_yes");
    });

     $("a.fav_yes").on('click', function () {
        var id = $(this).attr("id");
        $(this).load("{$homepage}/user_action.php?action=remove_fav&id="+ id +"").removeClass("fav_yes");
    });

}

then you call initEvents on page load, and than again when html is replaced.