【问题标题】:Button JQuery event only working once, why?Button JQuery 事件只工作一次,为什么?
【发布时间】:2017-07-22 19:21:44
【问题描述】:
<script>
        $("button").on("click", function() {
            $.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1", function(json) {
                $(".author").html(json[0].title);
                $(".quote").html('"'+json[0].content+'"');
            });
        });

    </script>

情况:我点击,数据加载完毕。我再次点击,没有任何变化。

Codepen: http://codepen.io/anon/pen/vxGgaZ

参考:https://quotesondesign.com/api-v4-0/

【问题讨论】:

  • 控制台有错误吗?显然,在第一次 getJSON 调用之后什么都不会发生,因为您已经第一次渲染了 html。如果请求没有第二次触发,那么您需要检查错误。
  • 您确定服务器上的数据在点击之间发生变化吗?
  • 按钮是.author 和/或.quote 的子元素吗?如果是这样,您必须使用 event-delegation 才能正常工作
  • @empiric 不是孩子。
  • @CamJohnson26 您可以通过网址自行查看。它会改变。

标签: javascript jquery ajax rest api


【解决方案1】:

试试这样:

也许对你有帮助

<script>
        $(document.body).on("click", 'button', function() {
            $.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1", function(json) {
                $(".author").html(json[0].title);
                $(".quote").html('"'+json[0].content+'"');
            });
        });

    </script>

【讨论】:

  • 没有改变任何东西。
【解决方案2】:

问题是因为第一个响应被缓存了。您可以通过添加一个停止缓存的$.ajaxSetup() 调用来解决这个问题:

$.ajaxSetup({
  cache: false
})

Updated Codepen

或者,使用$.ajax() 并直接在设置中设置cache

$("button").on("click", function() {
  $.ajax({  
      url: 'http://quotesondesign.com/wp-json/posts',
      type: 'get',
      cache: false,
      data: 'filter[orderby]=rand&filter[posts_per_page]=1', 
      success: function(json) {
        $(".author").html(json[0].title);
        $(".quote").html('"' + json[0].content + '"');
      }
  });
});

【讨论】:

  • 这就是我正在寻找的,不记得确切的代码
  • 资源是否使用 CORS 标头提供服务?
  • @RoryMcCrossan 仍然没有找到导航 codepen 界面的方法。 stacksn-ps 使用http://null 作为来源,但能够使用 plnkr 的&lt;link&gt; 元素获取资源。注意);success javascript 在问题上。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-09
  • 2011-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-05
  • 2012-09-21
相关资源
最近更新 更多