1
這裏是我的代碼,現在有些人可能會說爲什麼不只是在該功能塊中包含一行代碼,但我不想,我該如何實現這一點。我怎麼能叫this.click
方法上 「點擊」 事件按鈕的javascript中的「click」事件嵌套函數調用
var i = 0;
function el() {
this.type = "button",
this.el = false,
this.click = function() {
this.setHtml(i++);
},
this.setHtml = function (t) {
this.el.innerHTML = t;
}
fragment = document.createDocumentFragment(),
element = fragment.appendChild(document.createElement(this.type));
element.setAttribute("data-el", this.type);
element.innerHTML = "Default Button";
this.el = element;
attachEvent("click", this);
}
// this should be a seperate function ....
function attachEvent(ev, me){
//me doesn't work, but i want it to call the click method
me.el.addEventListener("click", me.click, false);//....
}
div = new el();
document.getElementById('areaA').appendChild(div.el);
+1問題是函數的上下文,用bind可以選擇「this」上下文,這裏是關於什麼是綁定的鏈接:https://developer.mozilla.org/en-US/docs/Web/ JavaScript/Reference/Global_Objects/Function/bind – Kalamarico
這太酷了,謝謝 –