weixin_33713707 2017-09-15 18:30 采纳率: 0%
浏览 13

AJAX第二次通话不起作用

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

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.

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

  • 写回答

1条回答 默认 最新

  • local-host 2017-09-15 18:45
    关注

    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>. 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:

    $(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>*");
           },
       });
    })
    
    评论

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突