简体   繁体   中英

How do i add an individual onclick/EventListener function to each row of PHP generated content?

Trying to expand PHP generated divs individually with an onclick event. How do I add an EventListener or onclick function to each div object so that I can expand them individually by clicking on them?

Right now i want to do something like this:

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

In a for loop:

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;
}

Since document.getElementsByClassName('card') returns a HTMLCollection of elements and not a single item, you will have to loop through your cards to attach the event.

Like this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM