【问题标题】:How to add Event Listeners in elements created from Template Literals?如何在从模板文字创建的元素中添加事件侦听器?
【发布时间】:2019-07-25 05:34:26
【问题描述】:

我创建了一个与 Twitter 具有相同功能的网站。我有一个名为“.post-template”的类,它是一个 div,用于您创建的每个帖子/推文。在这个 div 中,有一个“评论”图标。现在的问题是我在上面放了一个函数,但只有硬编码的有事件监听器。从模板文字创建的新元素没有事件侦听器/函数。

我尝试了不同类型的选择器,但它并不真正适用于模板文字中新创建的元素。我还使用了我认为可以使用的“insertAdjacentHTML”,但它也仅适用于硬编码文本。

// 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. */

【问题讨论】:

  • 在使用newsFeed.insertAdjacentHTML 附加新创建的元素后,在clickPeach2 函数内的新创建元素上添加侦听器。 comment 变量包含当时可用的所有 cmets,但它不会包含新创建的元素,因为当使用 document.querySelectorAll 分配变量时它们还不可用。
  • 为什么不使用委托监听器?
  • @AayushSharma 感谢您的建议!它目前正在运行。

标签: javascript html css


【解决方案1】:

您应该使用 jquery 选择最后创建的子元素,并在每次创建新元素时添加事件侦听器。例如:const element = $('.yourClassName').last(); 之后,只需将事件监听器添加到该元素。 element.addEventListener();

【讨论】:

  • yourClassName 这里是你想要添加事件监听器的元素的类名。
  • 也可以使用 document.createElement(), element.appendChild() 和类似的函数。你的方法效率很低。
  • 因推荐 jQuery 而被否决。另请注意,jQuery 对象没有addEventListener。你必须做const element = $('.yourClassName').last()[0];获取 DOM 元素。
  • 建议jquery有什么问题?大多数大公司都在使用它。如果他要使用 javascript 和 DOM,他无论如何都应该使用 jquery。
  • jQuery 已成为过去。我接触的大多数项目都花费时间和金钱来摆脱 jQuery。
猜你喜欢
  • 1970-01-01
  • 2021-10-12
  • 2022-08-14
  • 1970-01-01
  • 2021-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-24
相关资源
最近更新 更多