【问题标题】:AJAX Second call doesn't workAJAX 第二次调用不起作用
【发布时间】:2017-09-15 18:30:50
【问题描述】:

我正在尝试做一个简单的投票按钮,但每次重新加载每个帖子只能工作一次。

它应该如何工作: 单击“+”-> 更新查询(在 django 中)-> 重新加载 div(将“+”更改为“-”)-> 允许单击“-”以撤消投票

它在我第一次投票后显示“-”按钮,但当我点击它时,没有任何反应。只有当我点击“F5”并重新加载页面时它才有效。

控制台没有错误。

        ... some django scripts to check which button should be displayed ...

         <span class="upvote"><span postId="{{post.id}}" class="vote" href="upvote/{{post.id}}">+</span></span>

         <span class="downvote"><span postId="{{post.id}}" class="vote" href="downvote/{{post.id}}">-</span></span>
         ...

        $(document).ready(function(){
          $(".vote").click(function(e){
          href = $(this).attr("href");
          postId = $(this).attr("postId");
          $.ajax({
                url: href,
                success: function() {
                    $("#post-"+postId+" >header").load(location.href+ " #post-"+postId+">header>*");
                },
           });
        });

正确填写“postId”和“href”属性

【问题讨论】:

标签: javascript jquery ajax


【解决方案1】:

根据您发布的代码,问题出在哪里并不明显,但我猜&lt;span&gt;-&lt;/span&gt; 是在您点击&lt;span&gt;+&lt;/span&gt; 之后添加到DOM 中的。如果是这种情况,那么您的问题是您仅将 $('.vote').on('click'... 绑定到了在页面加载时首次执行该代码时 DOM 中的 .vote 元素。您可以通过使用事件委托将事件处理程序绑定到静态父元素并处理来自与您的选择器匹配的子元素的任何事件来解决此问题:

$(document).on('click', ".vote", function(e){
    href = $(this).attr("href");
    postId = $(this).attr("postId");
    $.ajax({
       url: href,
       success: function() {
          $("#post-"+postId+" >header").load(location.href+ " #post-"+postId+">header>*");
       },
   });
})

【讨论】:

    猜你喜欢
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    • 2018-06-15
    相关资源
    最近更新 更多