如何在PHP生成的内容的每一行中添加单独的onclick / EventListener函数?

时间:2019-03-28 19:10:06

标签: javascript php html css

尝试通过onclick事件分别扩展PHP生成的div。如何为每个div对象添加EventListener或onclick函数,以便单击它们可以分别展开它们?

现在我想做这样的事情:

document.getElementsByClassName('card').addEventListener('click', function() {
  document.getElementsByClassName('card').classList.toggle('expand');
});

在for循环中:

echo "<div class='card z-depth-1'>
      <div class='event-text'>
      <p class='event-time white-text'>" . date('H:i',strtotime($array[$i]['DTSTART'])) . "</p>
      <p class='event-information red-text text-lighten-4'>" . explode("\\,", $array[$i]['SUMMARY'])[0] . " " . $type . " " . str_replace('Lokal : ', '', $array[$i]['LOCATION']) . "</p>
      <p><br><br>Lorem ipsum leo cursus commodo quam dapibus metus dictumst etiam, quisque posuere ut molestie quam ad duis neque quis adipiscing posuere cras vulputate augue curae, leo lacinia diam ullamcorper aenean, ipsum donec luctus quam ad.</p>
      </div>
      </div>
      </div>";

CSS:

.card {
  max-height: 10vh;
  overflow: hidden;
}
.card.expand {
  max-height: 20vh;
  overflow: hidden;
}

1 个答案:

答案 0 :(得分:2)

由于document.getElementsByClassName('card')返回了HTMLCollection个元素而不是单个项目,因此您将不得不遍历卡片以附加事件。

赞:

var cards = document.getElementsByClassName('card');

for (let card of cards) {
  card.addEventListener('click', function() {
    this.classList.toggle('expand');
  });
}