2010-06-22 99 views
0

我已經bulid一個js類,它是有控制(HTML控件)參數,我嘗試dinamicly onchange事件添加到控件,但我有如下因素的錯誤:JS錯誤:HTMLFILE:未實現

HTMLFILE:未實現

//-------------- the code 

Contrl.prototype.AddChangeEvent = function() { 

    var element = this.docID; 
    var fn = function onChange(element) { 

    // action 



    }; 

    if (this.tag == "input" && (this.el.type == "radio")) { 
     this.el.onclick = fn(element); // there i have the error 
    } 
    else { 
     this.el.onchange = fn(element); // there i have the error 
    } 
} 

回答

1

通過寫this.el.onclick = fn(element),你調用fn立即,並指派任何fn返回onclick

你需要讓調用fn你想讓它變得參數匿名函數,像這樣:

this.el.onclick = function() { return fn(element); }; 

然而,這不是分配事件處理程序在JavaScript中正確的方法。

你應該叫attachEvent(IE瀏覽器)或addEventListener(其他一切),是這樣的:

function bind(elem, eventName, handler) { 
    if (elem.addEventListener) 
     elem.addEventListener(eventName, handler, false); 
    else if (elem.attachEvent) 
     elem.attachEvent("on" + eventName, handler); 
    else 
     throw Error("Bad browser"); 
} 
+0

不僅打電話,但結合this.el.onclick – user368038 2010-06-22 15:04:36

+0

@haroldis:不,你不是綁定它。你正在試圖綁定它,但你沒有成功。 – SLaks 2010-06-22 15:07:23