首页 > 解决方案 > jQuery 最喜欢的函数调用 api 与 ajax

问题描述

我正在尝试在我的 django 模板中创建一个最喜欢的函数,让用户单击该图标,它将调用我制作的一个 api,以从用户数据中发送添加和删除该最喜欢的项目。

最喜欢和不喜欢的按钮

目前它是如何工作的,如果用户点击图标(最喜欢的或不喜欢的),它将调用一个处理添加收藏或删除收藏的api,并且它还将用相反的标签替换该标签的DOM(例如,如果我点击最喜欢的然后它的整个标签将被替换为具有不喜欢的图标和点击功能的标签内容)

这里是我的标签的 html,它显示基于它是否是最喜欢的({% %} 标签是 django 处理它):

<div class="article-category">{{ property.get_type_display }}
     <div class="bullet"></div> {{ property.publish_date|date:'d-m-Y' }}
     {% if not request.user|is_favorite:property.id %}
         <a id="mylink" href="javascript:onclickFunction()" value="{{ property.id }}">
            <i class="far fa-heart fa-lg" style="color: red" title="Add to favorite"></i>
         </a>
      {% else %}
          <a id="mylink2" href="javascript:onclickFunction()" value="{{ property.id }}">
             <i class="fas fa-heart fa-lg" style="color: red" title="Remove from favorite"></i>
          </a>
      {% endif %}
 </div>

这是我的 jquery 脚本:

<script>
    $(document).ready(function () {
            $('#mylink').on('click', function (event) {
                event.preventDefault();
                property_id = $(this).attr("value")
                $.ajax({
                    type: "POST",
                    url: "http://localhost:9999/api/add_favorite/" + property_id + "/",
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('Authorization', 'Bearer {{ refresh_token }}');
                    },
                    success: function (data) {
                        if (data.code == 200) {
                            alert('ok');
                            replace_part_1 = '<a id="mylink2" href="javascript:onclickFunction()" value="' + property_id +'"><i class="fas fa-heart fa-lg" style="color: red" title="Remove from favorite></i></a>'
                            $("#mylink").replaceWith(replace_part_1);
                        }
                    }
                });
                return false;
            });
            $('#mylink2').on('click', function (event) {
                event.preventDefault();
                property_id = $(this).attr("value")
                $.ajax({
                    type: "DELETE",
                    url: "http://localhost:9999/api/remove_favorite/" + property_id + "/",
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('Authorization', 'Bearer {{ refresh_token }}');
                    },
                    success: function (data) {
                        if (data.code == 200) {
                            alert('ok');
                            replace_part_2 = '<a id="mylink" href="javascript:onclickFunction()" value="' + property_id +'"><i class="far fa-heart fa-lg" style="color: red" title="Add to favorite"></i></a>'
                            $("#mylink2").replaceWith(replace_part_2);
                        }
                    }
                });
                return false;
            });
        });
</script>

现在我第一次点击最喜欢或不喜欢它发送到 api 并工作,“#mylink2”onclick 事件的替换 html 部分,但“#mylink”替换不包括包含图标的标签。

在此之后,任何单击事件都将不起作用,我必须刷新页面才能再次单击它才能工作。之后的任何点击事件也会返回此错误:

未捕获的 ReferenceError:onclickFunction 未定义于 :1:1

我是 jquery 的超级菜鸟,所以我似乎找不到问题所在,希望有人能帮助我

编辑:

我通过替换锚标记的值属性将我的脚本更改为:

<script>
    $(document).ready(function () {
            $('.article-details').on('click', '#mylink', function(event) {
                event.preventDefault();
                property_id = $(this).attr("value")
                $.ajax({
                    type: "POST",
                    url: "http://localhost:9999/api/add_favorite/" + property_id + "/",
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('Authorization', 'Bearer {{ refresh_token }}');
                    },
                    success: function (data) {
                        if (data.code == 200) {
                            alert('ok');
                            replace_part_1 = '<a id="mylink2" href="#" value="' + property_id +'"><i class="fas fa-heart fa-lg" style="color: red" title="Remove from favorite></i></a>'
                            $("a[value='" + property_id + "']").replaceWith(replace_part_1);
                        }
                    }
                });
                return false;
            });
            $('.article-details').on('click', '#mylink2', function(event) {
                event.preventDefault();
                property_id = $(this).attr("value")
                $.ajax({
                    type: "DELETE",
                    url: "http://localhost:9999/api/remove_favorite/" + property_id + "/",
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('Authorization', 'Bearer {{ refresh_token }}');
                    },
                    success: function (data) {
                        if (data.code == 200) {
                            alert('ok');
                            replace_part_2 = '<a id="mylink" href="#" value="' + property_id +'"><i class="far fa-heart fa-lg" style="color: red" title="Add to favorite"></i></a>'
                            $("a[value='" + property_id + "']").replaceWith(replace_part_2);
                        }
                    }
                });
                return false;
            });
        });
</script>

和我的 html 到:

<div class="article-category">{{ property.get_type_display }}
                                <div class="bullet"></div> {{ property.publish_date|date:'d-m-Y' }}
                                {% if not request.user|is_favorite:property.id %}
                                <a id="mylink" href="#" value="{{ property.id }}">
                                    <i class="far fa-heart fa-lg" style="color: red" title="Add to favorite"></i>
                                </a>
                                {% else %}
                                <a id="mylink2" href="#" value="{{ property.id }}">
                                    <i class="fas fa-heart fa-lg" style="color: red" title="Remove from favorite"></i>
                                </a>
                                {% endif %}
                            </div>

它起作用了,但是更改html时#mylink的onclick仍然消失了(#mylink2 onclick起作用了,它改变了html白色标签)

标签: javascriptjqueryhtmlajaxdjango-templates

解决方案


看起来您正面临事件委托问题。也就是说,当您的 jQuery 代码运行时,$('#mylink2')文档中不存在,因此事件不会被绑定。改用事件委托

$('.article-category').on('click', '#mylink2', function(event) {
   event.preventDefault();
   // your original click handler
});

#myParentWrapper应该是标记中一致的元素,最好不要bodydocument出于性能原因。

然后,您可以从您的锚点中删除 onclick 属性 - 或者 - 实际上,如果它应该执行您的 jQuery 代码已经执行的操作之外的任何操作,那么它实际上是在某个地方定义了在那里引用的函数。


推荐阅读