单击数组中的每个ID

时间:2019-04-22 11:50:49

标签: javascript php

我需要能够遍历数组中的每个项目并单击它。该数组表示需要单击的元素的ID。 这是检索数组并将其放入变量arrayResponse

的代码
  

// [“ 2”,“ 3”,“ 4”,“ 5”,“ 1”,“ 2”,“ 3”,“ 4”,“ 5”]

function reqListener () {
  console.log(this.responseText);
}

var oReq = new XMLHttpRequest(); //New request object
oReq.onload = function() {

//The actual data is found on this.responseText
  var arrayResponse = this.responseText; //Assign array to variable
  alert(arrayResponse);

  arrayResponse.forEach(function(entry) {
  //Click through array here
});
};
oReq.open("get", "load.php", true);
oReq.send();

HTML

 <img id="1" class="image" src="ON-Green.png">

2 个答案:

答案 0 :(得分:1)

我认为图像具有ID条目。

arrayResponse.forEach(function(entry) {
document.getElementById(entry).click(); //using js
$("#"+entry).click(); //using jquery
});

答案 1 :(得分:0)

您已经有一个foreach循环来获取每个单独的循环,您需要单击每个ID,
按照我的示例:

function reqListener () {
  console.log(this.responseText);
}

var oReq = new XMLHttpRequest(); //New request object
oReq.onload = function() {

//The actual data is found on this.responseText
var arrayResponse = this.responseText; //Assign array to variable
alert(arrayResponse);

arrayResponse.forEach(function(entry) {
      document.querySelector('#'+entry).click();
});
};
oReq.open("get", "load.php", true);
oReq.send();