javascript - 如何在点击事件上更新 HTML 元素?

标签 javascript jquery html

我对编程真的很陌生,我正在尝试构建一个随机报价机。 用户应该能够在单击“新报价”按钮后获得新的随机报价。 我的问题是,第一次单击“新报价”按钮时,我得到了一个新报价,但随后的单击事件中报价不再改变。有人可以确定我的代码中的问题出在哪里吗?

这是我的 HTML:

<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" />

<div class="container-fluid">

  <div class="header">
    <h1 class="title"> Antsa's Random Quote Machine </h1>

  </div>

  <div class="quote_box">

    <div class="col-xs-12 well quote">
      Quote will go here
    </div>

    <div class="row col-xs-12">
      <a href="https://twitter.com/antsarand" target="_blank"><button class ="btn btn-primary"><i class="fa fa-twitter" id="twitter"></i> </button></a>

      <button id = "newQuote" class = "btn btn-primary">
        New Quote
      </button>
    </div>


    </div>

  </div>
</div>

这是我的 JavaScript 代码:

$(document).ready(function() {

   $("#newQuote").on("click", function() {
     $.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1", function(json) {
       var html = "";
       json.forEach(function(val) {

         html += "<div class = 'quote'> ";

         html += "<p class = 'quotation'>" + val.content + val.title + "</p>";

         html += "</div>";
       });
       $(".quote").html(html);
     });

   });
 });

最佳答案

不要相信示例(不检查控制台)

您的代码应该可以正常工作,Codepen 示例不支持跨源请求,因此它们会阻止您的 AJAX 调用:

enter image description here

但是如果你 use a different example provider like JSBin它们应该按预期工作:

enter image description here

缓存要缓存

如果您计划在同一页面内发出多个请求,请考虑通过 jQuery 代码中的以下语句显式禁用缓存:

$.ajaxSetup({ cache: false });

这将防止发生任何缓存并确保每次都会提取新的报价。

需要更多吗?

最后,您会注意到查询字符串参数之一似乎准确指定了要提取的记录数[posts_per_page]=1。如果您想检索多个引号并实际使用 forEach() 函数,您可能需要对此进行调整。

关于javascript - 如何在点击事件上更新 HTML 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37328866/

相关文章:

jquery - 如何动画化 CSS 翻译

php - 折叠/展开表格中的 div?

javascript - 使用 Ember.$.ajax() 发送具有关系的数据

javascript - Angular/JavaScript 自动水合实例

javascript - 将 Chrome 扩展程序转换为 Opera 扩展程序

javascript - 如何在循环的 django 模板中创建唯一的 javascript 变量名?

javascript - addEventListener ('exit' ) 到 PhoneGap 中的 inappbrowser

javascript - 如何在 $ ('body' .append 脚本中添加这些 HTML 标签?

html - Svg 绝对中心 - 如何保持比例

javascript - 在 html 中嵌入本地 asciinema 文件