[英]Add event listener to template string in a render function
所以寫了一個簡單的腳本:
function Component(renderTarget){
this.target = document.querySelector(renderTarget);
this.number = 0;
this.increment = 1;
this.goUp = function(){
this.number = this.number + this.increment;
this.render();
}
this.goDown = function(){
this.number = this.number - this.increment;
this.render();
}
this.render = function(){
this.target.innerHTML = '';
this.target.innerHTML += `
<div class="container">
<div class="number">${this.number}</div>
<div class="selector">
<div class="up"><i class="fa fa-chevron-up" aria-hidden="true"></i></div>
<div class="down"><i class="fa fa-chevron-down" aria-hidden="true"></i></div>
</div>
</div>`;
}
this.init = function(that){
that.render();
}(this);
}
var myComponent = new Component('.target');
這基本上是將一些HTML呈現給具有“目標”類的div。 現在,我想向.up
和.down
添加一個事件偵聽.up
,並將它們綁定到組件函數。 哪個是正確的方法?
您可以分叉此Codepen 。
提前致謝! PS:我知道我可以使用class
和箭頭函數等,但這僅用於測試。
編輯: 工作版本 。 這可行,但我不知道這是否是正確的方法。
每個人及其姨媽都有自己的最佳實踐
這就是我的方法: codepen
this.target.querySelector('.up').addEventListener('click', this.goUp)
this.target.querySelector('.down').addEventListener('click', this.goDown)
渲染完成后,您需要添加事件監聽器。 除非您要將事件附加到目標並使用自定義邏輯委托事件。
我更喜歡將自己綁定到事件監聽器上
此外,您的工作版本因多個組件而失敗。 知道您可以對元素執行.querySelector
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.