【发布时间】: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