简体   繁体   English

jQuery脚本只能运行一次

[英]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. 在控制台中,单击多次(因此计算在内)后,单击时会得到文章(div)的ID,但它没有任何作用。 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. 如果要替换负责捕获事件的html,则应再次初始化那些事件捕获器。

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. 那么您会在页面加载时调用initEvents,然后在替换html时调用initEvents。

If you use the .on() overload that takes 3 args and is called on the document. 如果使用.on()重载,则需要3个args并在文档上调用。 Then the events will remain hooked up as UI elements come and go. 然后,事件将随着UI元素的来来去去。 No need to re add them every time. 无需每次都重新添加它们。

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

See the description of .on() here. 请参阅此处的.on()描述。 http://api.jquery.com/live/ http://api.jquery.com/live/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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