繁体   English   中英

AJAX第二次通话不起作用

[英]AJAX Second call doesn't work

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

运作方式:按一下[+]->更新查询(在django中)->重新载入div(将“ +”变更为“-”)->允许按一下[-]撤消upvote

第一次投票后,它显示“-”按钮,但是当我单击它时,什么也没有发生。 仅当我按“ 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”属性

根据您发布的代码,问题出在哪里并不明显,但是我猜测<span>-</span>您单击<span>+</span> 之后添加到DOM的。 如果.vote这样,那么您的问题是,仅在页面加载首次执行该代码时,才将$('.vote').on('click'... .vote到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>*");
       },
   });
})

暂无
暂无

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

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