gpt4 book ai didi

javascript - 小JS循环问题

转载 作者:行者123 更新时间:2023-11-28 15:23:37 25 4
gpt4 key购买 nike

我有一个从数据库调用数据的脚本。对于每个结果都会输出一个新的 div。但是,当单击调用函数 search() 的按钮时,我只得到一个结果。我想问题是:如何为每个结果创建一个新的 div,而不仅仅是将其设置为找到的第一行?

function search()   {
var xhr2 = new XMLHttpRequest();
xhr2.addEventListener ("load", view);
var reg = document.getElementById("type").value;
xhr2.open("GET", "getresults.php?type=" + reg);
xhr2.send();
}
function view(e, resulthtml) {
var array = JSON.parse(e.target.responseText);
for (var count=0; count<array.length; count++)
{
var id = array[count].id;
var username = array[count].username;
var srcpath = array[count].srcpath;
var title = array[count].title;
var type = array[count].type;
var postcode = array[count]. postcode;
var description = array[count]. description;
var price = array[count].price;
var phone = array[count].phone;
var lat = array[count].lat;
var lon = array[count].lon;

resulthtml = "<div class='col-md-4'>"
+ "<div class='thumbnail'>"
+ "<img id='a' class='a' alt='300x200' src='" + srcpath + "'>"
+ "<div class='caption'>"
+ "<h3>"
+ description
+ "</h3>"
+ "<p>"
+ "£" + price + ""
+ "</p>"
+ "<p>"
+ "Contact number:"
+ "</p>"
+ "<p>"
+ "<input type='submit' value='Contact seller' onclick='search()'/>"
+ "</p>"
+ "</div>"
+ "</div>"
+ "</div>"

}
document.getElementById("row").innerHTML = resulthtml;
}


</script>

最佳答案

您将在循环的每次迭代中覆盖 resulthtml。在循环外将其初始化为空字符串,然后添加到其中。

编辑:您还在循环中做了很多可以提升到循环之外的工作,主要是所有字符串连接。这在浏览器上会更容易:

var item, id, username, srcpath, title, type, postcode, description, price, phone, lat, lon,
resulthtml = '',
pre = "<div class='col-md-4'><div class='thumbnail'><img id='a' class='a' alt='300x200' src='",
inner1 = "'><div class='caption'><h3>",
inner2 = "</h3><p>£",
post = "</p><p>Contact number:</p><p><input type='submit' value='Contact seller' onclick='search()'/></p></div></div></div>";

for (var count=0; count<array.length; count++)
{
item = array[count];
id = item.id;
username = item.username;
srcpath = item.srcpath;
title = item.title;
type = item.type;
postcode = item. postcode;
description = item. description;
price = item.price;
phone = item.phone;
lat = item.lat;
lon = item.lon;

resulthtml += pre + srcpath + inner1 + description + inner2 + price + post;

}

关于javascript - 小JS循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30140680/

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