简体   繁体   中英

Button JQuery event only working once, why?

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

Situation: I click, the data is loaded. I click again, nothing changes.

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

Reference: https://quotesondesign.com/api-v4-0/

The problem is because the first response is being cached. You can solve that by adding a $.ajaxSetup() call which stops the caching:

$.ajaxSetup({
  cache: false
})

Updated Codepen

Alternatively, use $.ajax() and set cache directly in the settings:

$("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 + '"');
      }
  });
});

Try Like This:

Maybe it's help you

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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