2010-06-22 66 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