使用循环设置HTML文本

时间:2019-03-11 12:11:28

标签: javascript rest sharepoint

我当前正在针对SharePoint列表运行REST查询,并且尝试使用$()。text()脚本显示结果。我有它的工作,但会认为有一种更有效的方法。我有很多字段需要设置,但是它们是顺序编号的,只是认为应该有更好的方法。下面的示例:

#defining the number of rows and columns in the lattice array
n<-20
#creating a sample of n^2 values of either -1 or 1
x<-sample(seq(-1,1,by=2), n*n, replace=T)
#plotting an n*n array with each point randomised to 1 or -1
S<-array(x, dim=c(n,n))
#printing the array
print(S)
#Plotting the Lattice, red points are 1, white is -1
image(1:20,1:20,S,zlim=c(-1,1),ylab="Column Number",xlab="Row Number")
#Defining the average magnetisation
Mag<-(1/(n*n))*sum(S)
#Printing the average magnetisation
print(Mag)

等x20字段... 我在下面尝试过,但是我可以肯定地知道所有原因,因为这些原因都知道您在执行此操作无效。 “ divId”可以很好地加载,但是dataId显示的是文本“ data.d.results [0] .slot1” / 2/3 / etc,而不是实际的data.d.results:

$('#div1Id').text(data.d.results[0].slot1);
$('#div2Id').text(data.d.results[0].slot2);
$('#div3Id').text(data.d.results[0].slot3);

2 个答案:

答案 0 :(得分:1)

根据您的第一个示例的操作,我认为您想要这样做:

for (i = 1; i < 21; i++) {
    var divId = "#div" + i + "Id";

    // access the value from the "slot#" property of the object
    var data = data.d.results[0]['slot' + i];

    // get the correct div based on the id and then 
    // set its text to the value
    $(divId).text(data);
}

答案 1 :(得分:1)

您可以尝试使用forEach方法,或者如前所述,删除“ data.d.results [0] .slot”中的引号

var data = [{
  "id": 1,
  "Name": "Some Title 1",
  "number": "Number 1"
}, {
  "id": 2,
  "Name": "Some Title 2",
  "number": "Number 2"
}, {
  "id": 3,
  "Name": "Some Title 3",
  "number": "Number 3"
}];

//data.d.results[0] << you'd use this
data.forEach(elem => {
  document.getElementById("entries").innerHTML += elem.Name +"<br/>";
});
<div id="entries"></div>