简体   繁体   中英

jQuery script works only once

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!

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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM