for循环不起作用 - 我做错了什么?

时间:2017-05-09 15:19:39

标签: javascript loops for-loop

我是JavaScript新手。如果你能帮助我代码,我将不胜感激:谢谢!

我试图隐藏10个问题的答案,并在点击右键时显示​​它们! 当我点击任何按钮时,它只显示最后一个答案!

var ya = document.getElementsByClassName("A");
$(ya).hide();

for (var i = 0; i < 10; i++){
  var x = document.getElementsByClassName("idcheck");
  var z = x[i].id;

  console.log(x[i]);

  $(x[i]).click(function() {
    var y = document.getElementsByClassName(z);
    $(y).show();
  });
}

这是html:

<p>
  <button id="B<?php echo $drow['id'];?>" class="btn btn-primary idcheck" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
    Lösung der Aufgabe!
  </button>
</p>
    <td><b class="text-success A B<?php echo $drow['id'];?>"><?php echo $brow['answertext'];?></b></td>
    </tr>
<?php
}
?>

3 个答案:

答案 0 :(得分:1)

您的代码比它需要的更复杂。如果你使用jQuery,只需坚持使用jQuery。

$(".A").hide();  
$(".idcheck").on("click", function() {
  var id = this.id;
  $("." + id).show();
});

答案 1 :(得分:0)

1)如果你使用jquery,请使用jquery! 2)看一下在js中的作用域

$(".A").hide();

$(".idcheck").each(function(){
  $(this).click(function() {
    $("."+$(this).id).show();
  });
});

答案 2 :(得分:0)

在您的代码中,您使用了jQuery以及bootstrap特定元素。所以我假设你的页面有jQuery。

请查看以下代码段

注意:我已经清理了HTML结构并删除了不必要的引导程序特定类

$('.idcheck') // We select all elements with the given class
  .on('click', function() { // We attach a function for the 'click' event
    var currID = $(this).attr('id').replace(/^B/i, ''); // We get teh ID fo the clicked buttona and remove 'B' from the start of it to it it's index

    $('.B' + currID).show(); // We then use the index and generate a class selector to target the <td> tag to show it

  })
.A {
  display: none; // Hide the element initially
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <button id="B1" class="btn btn-primary idcheck" type="button">
        Button for ID 1
      </button>
    </td>
    <td><b class="text-success A B1">Content for ID 1</b></td>
  </tr>
  <tr>
    <td>
      <button id="B2" class="btn btn-primary idcheck" type="button">
        Button for ID 2
      </button>
    </td>
    <td><b class="text-success A B2">Content for ID 2</b></td>
  </tr>
</table>

相关问题