jQuery script works only once

十年热恋 提交于 2019-12-12 04:36:05

问题


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.



来源:https://stackoverflow.com/questions/18431416/jquery-script-works-only-once

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