document.querySelector只能读取1个类

时间:2018-09-20 19:33:26

标签: javascript php html

当我单击document.getElementById时,它仅执行第一个<ul>,我希望所有ul都在单击时起作用。

PHP

for ($i=0; $i < $Count_Assoc['dev'] ; $i++) { 

  $History_Assoc = mysqli_fetch_array($HistoryQuery);

  echo '<ul class="repoFolder" data-value="'. $History_Assoc['devaddr'] .'">';
  echo '<br>';

  echo '<h5 style=" color: black;
  padding: 0px 9em 0em 0em;">DevAddr:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspData:</h5>';
  echo '<p>'.$History_Assoc['devaddr'].'&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp'.$History_Assoc['data'].'</p>';

  echo "</ul>";
  echo '<br>';

}

JavaScript

document.querySelector('.repoFolder').onclick = function() {rootFolder()};

function rootFolder() {
  alert(document.querySelector('.repoFolder').getAttribute('data-value'));
}

3 个答案:

答案 0 :(得分:1)

您应该在列表中设置类别,而不是ID。 id应该是唯一的标识符,但是class是可以创建多个公共元素的方法。在这里,我将您的ID更改为类

for ($i=0; $i < $Count_Assoc['dev'] ; $i++) { 

  $History_Assoc = mysqli_fetch_array($HistoryQuery);

  echo '<ul class="repoFolder" data-value="'. $History_Assoc['devaddr'] .'">';
  echo '<br>';

  echo '<h5 style=" color: black;
  padding: 0px 9em 0em 0em;">DevAddr:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspData:</h5>';
  echo '<p>'.$History_Assoc['devaddr'].'&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp'.$History_Assoc['data'].'</p>';

  echo "</ul>";
  echo '<br>';

}

和JavaScript:

var folders = document.getElementsByClassName("repoFolder");
for (let i = 0; i < folders.length; i++) {
  folders[i].onclick = function() {rootFolder.call(this)}; // note that I am passing in the context to rootFolder. 
}

function rootFolder() {

  alert(this.getAttribute('data-value'));

}

答案 1 :(得分:1)

您可以使用querySelectorAll选择具有类repoFolter的所有元素,并遍历每个元素并追加eventListener

var elements = document.querySelectorAll('.repoFolder');
elements.forEach(function(el){
    el.addEventListener('click', rootFolder);
})

function rootFolder( ){ ... }

答案 2 :(得分:0)

来自w3schools.com

  

querySelector()方法返回与匹配的第一个元素   文档中指定的CSS选择器。

如果要获取具有特定类或名称的所有元素:

document.getElementsByClassName("text").onclick = function () {
    alert("Called");
}