简体   繁体   English

AJAX第二次通话不起作用

[英]AJAX Second call doesn't work

I'm trying to do a simple voting button but it works only one time per post per reload. 我正在尝试做一个简单的投票按钮,但每次重新加载后每个帖子只能使用一次。

How should it work: Click "+" -> update query (in django) -> reload a div (change "+" to "-") -> allow to click "-" to undo the upvote 运作方式:按一下[+]->更新查询(在django中)->重新载入div(将“ +”变更为“-”)->允许按一下[-]撤消upvote

It shows the "-" button after I vote for the first time but when I click it, nothing happens. 第一次投票后,它显示“-”按钮,但是当我单击它时,什么也没有发生。 It works only if I hit "F5" and reload the page. 仅当我按“ F5”并重新加载页面时,它才有效。

There are no errors in console. 控制台中没有错误。

        ... 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>*");
                },
           });
        });

The "postId" and "href" attributes are properly filled 正确填写了“ postId”和“ href”属性

It's not obvious what the problem is based on the code you posted, but I'm guessing that the <span>-</span> is added to the DOM after you have click on <span>+</span> . 根据您发布的代码,问题出在哪里并不明显,但是我猜测<span>-</span>您单击<span>+</span> 之后添加到DOM的。 If that is the case, then your problem is that you have only bound $('.vote').on('click'... to the .vote elements that were in the DOM when that code first executed on page load. You can fix this by using event delegation to bind the event handler to a static parent element and act on any events coming from children that match your selector: 如果.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