document.getElementsByClassName不起作用

时间:2018-06-13 20:36:45

标签: javascript html css

有谁知道它为什么不起作用?

我希望当我点击div odpoved时显示div dotaz

function ukaz(a) {
  var elements = document.getElementsByClassName(a);
  for (var i = 0; i < elements.length; i++) {
    elements[i].style.display = "block";
  }
}
<div class="dotaz" onClick="ukaz(odpoved)">
  <p>YOSODJDN</p>
  <span class="qanick">jirka</span>
  <span class="fafadown"><i class="arrow fa fa-angle-down" style="font-size:24px"></i></span>
</div>

<div class="odpoved" style="display:none">
  <p>ODPOVED</p>
  <span class="qanick">anetka</span>
</div>

2 个答案:

答案 0 :(得分:3)

像这样使用它,将odpoved作为字符串传递

<div class="dotaz" onClick="ukaz('odpoved')">

&#13;
&#13;
<div class="dotaz" onClick="ukaz('odpoved')">
<p>YOSODJDN</p>
<span class="qanick">jirka</span>
<span class="fafadown"><i class="arrow fa fa-angle-down" style="font- 
size:24px"></i></span>
</div>

<div class="odpoved" style="display:none">
<p>ODPOVED</p>
<span class="qanick">anetka</span> 
</div>


<script>
function ukaz(a) {
var elements = document.getElementsByClassName(a);
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = "block";
}
}
</script>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

onClick="ukaz(odpoved)"试图使用变量 - 而不是字符串 - 作为参数来调用函数。

function ukaz(a) {
  var elements = document.getElementsByClassName(a);
  for (var i = 0; i < elements.length; i++) {
      elements[i].style.display = "block";
  }
}
<div class="dotaz" onClick="ukaz('odpoved')"> <!-- odpoved is a string, not a variable -->
  <p>YOSODJDN</p>
  <span class="qanick">jirka</span>
  <span class="fafadown">
    <i class="arrow fa fa-angle-down" style="font-size:24px"></i>
   </span>
</div>

<div class="odpoved" style="display:none">
  <p>ODPOVED</p>
  <span class="qanick">anetka</span> 
</div>