我有这个AJAX请求:
kivy_image_widget.source = None
function getLocation() {
$.get('../class/info/act/all', function (locations) {
window.locations = locations;
var key = ["id", "name", "nodelist"];
for(var l = 0; l < locations.length; l++) {
var roomValue = {};
roomValue = locations[l];
var span = document.createElement("div");
for (var p = 0; p < key.length; p++) {
if(locations[l]){
var anchor = document.createElement('a');
anchor.classList.add("content" + l);
span.append(anchor);
var textContent = document.createTextNode(roomValue[key[p]]);
anchor.append(textContent);
$(".roomContent").append(span);
}
}
}
})
}
<div id="inner" class="roomContent">
</div>
我想要的是一个包含所有信息的元素,像这样:
After the request is done, the div is populated like this:
<div>
<a class=""content0">1</a>
<a class=""content0">ROOM1</a>
<a class=""content0">1,2</a></div>
有什么想法吗?有没有办法拆分信息?我搜索了一条线索,但没有找到任何东西
答案 0 :(得分:0)
在forloop之外添加:var span = document.createElement("div");
var anchor = document.createElement('a');
anchor.classList.add("content" + 0);
span.append(anchor);
答案 1 :(得分:0)
您需要在for循环之外创建并添加锚点,因此实际上只执行一次。
function getLocation() {
$.get('../class/info/act/all', function (locations) {
if(locations.length === 0) { //do nothing if there's nothing to do
return;
}
window.locations = locations; //window shouldn't be used to store unnecessary non-global variables, use correct scope
var key = ["id", "name", "nodelist"];
//prepare elements
var anchor = document.createElement('a');
var span = document.createElement("div");
//fill with values, set classes
for(var l = 0; l < locations.length; l++) {
var roomValue = {};
roomValue = locations[l];
for (var p = 0; p < key.length; p++) {
if(locations[l]){ //this is unnecessary as it is always true - you're already iterating through the array
anchor.classList.add("content" + l);
var textContent = document.createTextNode(roomValue[key[p]]);
anchor.append(textContent);
}
}
}
//append prepared elements
span.append(anchor);
$(".roomContent").append(span);
})
}