【发布时间】:2018-01-09 15:30:45
【问题描述】:
让我从头开始。我正在开发一个包含两个组件text area 的网站:不是输入文本区域,而是well,只要单击按钮,就会出现文本。第二个组件是button,单击它时,well 中会出现一个随机引用。单击此按钮会调用部署在外部服务器上的 API,其中 Access-Control 未设置为 public。此 API 从包含许多引用及其作者的数据库中获取数据。以 JSON 格式。
现在,为了绕过这个Access-Control,我使用了 JSON Padding `JSONP.
但这里的目标是,每当使用 jQuery 调用 API 时,即每当单击按钮时,查询都必须通过触发 API 来获取随机引用。而且,每当单击按钮时,引用必须不断更改为新引用。
这是我的代码:
$(document).ready(function() {
$("#click").each(function(index){
$(this).on("click", function() {
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=?", function(key) {
$("#quote span").replaceWith(key[0].content + "<p>— " + key[0].title + "</p>");
});
});
});
});
});
<style>
.position-message{
margin-left: 25%;
margin-right:25%;
margin-top:10%;
margin-bottom:20%;
}
.background{
background-color: rgb(170,180,200);
border-radius:10%;
}
.button-shape{
border-radius: 50%;
width: 50px;
height: 50px;
margin: auto;
}
#page{
margin-left: 5%;
margin-right: 5%;
margin-top:2%;
margin-bottom:2%;
}
#page-background{
background-color: maroon;
}
#click{
margin-bottom: 20px;
}
.quote-shape{
border-radius: 10%;
}
</style>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700&lang=en" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<Title>Click to get quotes</Title>
<body id="page-background">
<div class="background" id="page">
<div class="container-fluid">
<div class="col">
<div class="row-xs-6">
<div id="quote" class="well position-message quote-shape"><span></span>
</div>
</div>
<div class="row-xs-6">
<div class="row text-center">
<button type="button" id="click" class="button-shape"><i class="fa fa-refresh fa-2x"></i>
</button>
</div>
</div>
</div>
</div>
</body>
</html>
第一个电话有效。但是当我尝试通过单击按钮再次触发 API 时,报价没有改变。这是我面临的问题。请让我知道如何在触发 API 时更改报价。
【问题讨论】:
-
仅供参考,这个
$("#click").each(function(index){ $(this).on("click", function() {是不必要的。$('#click').on('click', function () {也可以。 -
$("#click").each没有意义。#click中的#按 ID 进行选择,并且 HTML ID 必须是唯一的,因此循环只会在它可以定位的单个可能元素上循环一次。 -
@ADyson 是的,也是。即使它是一个类并且该类有多个元素,
each也是多余的。 -
无论如何,问题是你只是用一些文本替换了跨度,所以下次你运行它时,没有插入内容的跨度。下面的答案应该可以解决它。
标签: javascript jquery html css json