gpt4 book ai didi

jQuery AJAX 每个循环使用append 和html

转载 作者:行者123 更新时间:2023-12-01 07:08:03 26 4
gpt4 key购买 nike

我想从下面的代码中检索 json 文件的数据,但问题是,如果我再次按下按钮,我会看到两倍的结果。我将每个循环的第一个附加更改为 html,但随后仅加载 json 的最后一个对象。

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() : Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

您可以使用 JQuery one()这将触发一次点击:

$("#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 .

希望这有帮助。

<小时/>

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,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36366750/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com