gpt4 book ai didi

javascript - ajax 脚本中的 HTML 过多?

转载 作者:行者123 更新时间:2023-11-30 12:42:23 28 4
gpt4 key购买 nike

我读到这个page附加很多元素是不好的做法,我应该在循环的每次迭代期间构建一个字符串,然后将 DOM 元素的 HTML 设置为该字符串。在循环中使用过多的 HTML 是否也是如此?

我有一个解析 JSON 数据的 AJAX 脚本。它需要向不同的现有元素添加数据,如下所示:

$.ajax({
url: "url",
success: function (data) {

$(data.query.results.json.json).each(function (index, item) {
var title = item.title, // A,B,C or D
age = item.age,
background = item.background,
ingredient = item.Ingredient;
$('.'+ title+'_ingredient').html(''+ingredient+'')
$('.'+ title+'_age').html(''+age+'')
$('.'+ title+'_background').html(''+background+'')
});
},
error: function () {}
});

HTML:

  <div class="A_ingredient"></div>
<div class="B_ingredient"></div>
<div class="C_ingredient"></div>
<div class="D_ingredient"></div>
<div class="A_age"></div>
<div class="B_age"></div>
<div class="C_age"></div>
<div class="D_age"></div>
<div class="A_background"></div>
<div class="B_background"></div>
<div class="C_background"></div>
<div class="D_background"></div>

是否需要先建立一个字符串?如果是这样,你能告诉我怎么做吗?

最佳答案

这纯粹是关于处理对 html() 的调用所花费的时间,因此他们只是建议您减少调用次数。在这种情况下,您可以在循环中构建它们一次,然后为每个设置一次 div html。

更新:

根据您的更新,除了您不需要添加的所有额外尾随引号(字符串是字符串是字符串)之外,您的代码没有问题。 您只能击中每个项目一次。

例如

$.ajax({
url: "url",
success: function (data) {

$(data.query.results.json.json).each(function (index, item) {
var title = item.title, // A,B,C or D
age = item.age,
background = item.background,
ingredient = item.Ingredient;
$('.'+ title+'_ingredient').html(ingredient);
$('.'+ title+'_age').html(age);
$('.'+ title+'_background').html(background);
});
},
error: function () {}
});

注意:如果您的项目属性(Age、Background、Ingredient)是简单值(不是对象或数组),您不需要前导 ''+要么。

上一个

假设你真的想连接结果(你现在只保留最后一个成分),你可以这样做:

例如

$.ajax({
url: "url",
success: function (data) {
var ingredients = '';
$(data.query.results.json.json).each(function (index, item) {
var title = item.title;
var ingredient = item.Ingredient;
ingredients += ingredient;
});
$('.aclass').html(ingredients);
$('.bclass').html(ingredients);
$('.cclass').html(ingredients);
$('.dclass').html(ingredients);
},
error: function () {}
});

可以简化为:

        $('.aclass,.bclass,.cclass,.dclass').html(ingredients);

您的示例中每个 div 的内容都相同,因此您只需要一个字符串。

在这种情况下,您可能需要在成分之间使用某种形式的分隔符,但您的示例太模糊了。

例如

 ingredients += ingredient + '<br/>';

关于javascript - ajax 脚本中的 HTML 过多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23949997/

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