简体   繁体   中英

How to add Event Listeners in elements created from Template Literals?

I created a website which has the same features like Twitter. I have a class called '.post-template' which is a div that is for every post / tweet that you create. In this div, there's a 'Comment' icon. Now the problem is I put a function on it but only the hard coded has Event Listeners. The new elements created from the Template Literals does not have event listeners / functions.

I've tried different kinds of selectors but it doesn't really work on the newly created elements from the Template Literals. I've also used the 'insertAdjacentHTML' which I thought would work but it only worked on the hard-coded text as well.

// This is the declaration for the comment icon
const comment = document.querySelectorAll('i.far.fa-comment');

/*
* This is the function for the Peach Button on the
* Center Bar which enables the end-user to post a
* tweet / peach and it just stacks below which is
* similar to the functionality of Twitter.
*/

peachButton2.addEventListener('click', clickPeach2);

function clickPeach2(){
    let SPValue = SPTextarea.value;
    let userIdentity = localStorage.getItem('username');
    if(SPValue !== ''){
    let sampleTemplate = `
      <!-- Post Template -->
      <div class="post-template">
          <div class="firstPart">
            <img class="profile-icon" src="your-icon.png">
          </div>
        <div class="posted-text">
           <h3>${userIdentity}</h3>
             <p>${SPValue}</p>
             <i class="far fa-comment"></i>
             <i class="fas fa-retweet"></i>
             <i class="far fa-heart"></i>
             <i class="far fa-share-square"></i>
        </div>
      </div>
      <!-- End of Post Template -->
        `;
    newsFeed.insertAdjacentHTML('afterBegin', sampleTemplate);
        SPTextarea.value = '';
    }
    else{
        console.log('No value');
    }
}

/*
* This is function for the icons when you
* post on the center bar. It changes the
* background and adds functionality.
*/

comment.forEach(cmt => {
  cmt.addEventListener('click', () => {
    cmt.style.color = '#fff';
    cmt.style.background = '#3399FF';
  });
});

/** I expected for all the Comment Icons to work especially the new div element created from the Template Literals in Javascript. */

You should use jquery to select the last child created and add event listener to that everytime a new element is created. For example: const element = $('.yourClassName').last(); After you do that just addEventListener to that element. element.addEventListener();

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