jQuery AJAX每个循环都使用append和html [英] jQuery AJAX each loop using append and html
问题描述
我想从下面的代码中检索json文件的数据,但是问题是,如果我再次按下该按钮,则会看到两倍的结果.我将每个循环的第一个附加项更改为html,但随后仅加载了json的最后一个对象.
I want from the following code to retrieve the data of the json file but the problem is that if I press again the button I see twice the results. I changed the first append of my each loop to html but then only the last object of my json is loaded.
HTML:
<ul id="myorders"></ul>
<button type="button" id="add-order">Load the orders</button>
JS:
$("#add-order").click(function(){
$.getJSON('API/orders.json', function(data){
$.each(data, function(i, order){
$("#myorders").append("<p><li> id: " + data[i].order.id + "</li>");
$("#myorders").append("<li> Name: " + data[i].order.name + "</li>");
$("#myorders").append("<li> Drink: " + data[i].order.drink + "</li></p>")
});
});
});
数据示例:
[{ "order":{"id": "1",
"name": "Bill",
"drink": "Capuccino"}},
{ "order":{"id": "2",
"name": "Sofia",
"drink": "Late"
}}]
推荐答案
工作中的小提琴 .
Working fiddle.
.one() :将处理程序附加到事件要素.每种事件类型的每个元素最多只能执行一次处理程序.
.one() : Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
您可以使用JQuery one()
一次触发点击:
You could use JQuery one()
that will trigger the click one time :
$("#add-order").one("click", function(){
$.getJSON('API/orders.json', function(data){
var my_orders = $("#myorders");
$.each(data, function(i, order){
my_orders.append("<li> id: " + data[i].order.id + "</li>");
my_orders.append("<li> Name: " + data[i].order.name + "</li>");
my_orders.append("<li> Drink: " + data[i].order.drink + "</li>")
});
});
});
注意::您附加了无效的HTML,<li>
标记应为ul
的直接子代,因此应删除p
.
NOTE : You append invalid HTML, <li>
tag should be a direct child of ul
so you should remove p
.
希望这会有所帮助.
var data = [{ "order":{"id": "1",
"name": "Bill",
"drink": "Capuccino"}},
{ "order":{"id": "2",
"name": "Sofia",
"drink": "Late"
}}]
$("#add-order").one("click", function(){
var my_orders = $("#myorders");
$.each(data, function(i, order){
my_orders.append("<li> id: " + data[i].order.id + "</li>");
my_orders.append("<li> Name: " + data[i].order.name + "</li>");
my_orders.append("<li> Drink: " + data[i].order.drink + "</li>")
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="myorders"></ul>
<button type="button" id="add-order">Load the orders</button>
这篇关于jQuery AJAX每个循环都使用append和html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!