2012-05-20 196 views
1

如何从HTML链接执行JS对象的函数属性? 我有以下JS:从HTML调用JavaScript函数

function Tester(elem) { 
    this.elem = document.getElementById(elem); 
} 

Tester.prototype.show = function() { 
    this.elem.innerHTML = '<a href="javascript: this.test();">test</a>'; 
}; 

Tester.prototype.test = function() { 
    alert("a"); 
}; 
​ 

下面是HTML:

<script type="text/javascript"> 
    var test = new Tester("test"); 
    test.show(); 
</script> 

当我点击获取呈现的链接,它无法识别的test()功能。我如何得到它,所以当用户点击链接时,test()函数被执行?

回答

4

的正确方法是创建一个DOM元素和附加事件处理程序的JavaScript:

Tester.prototype.show = function() { 
    var a = document.createElement('a'), 
     self = this; // assign this to a variable we can access in the 
        // event handler 

    a.href = '#'; 
    a.innerHTML = 'test'; 
    a.onclick = function() {  
     self.test(); 
     return false; // to prevent the browser following the link 
    }; 

    this.elem.appendChild(a); 
}; 

由于事件处理形成closure,它可以访问到外部函数定义的变量(Tester.prototype.show )。请注意,在事件处理程序中,this不引用您的实例,而是引用处理程序绑定的元素(在此例中为a)。 MDN has a good description of this

quirksmode.org有一些great articles有关事件处理时,可以将事件处理程序,其优点和缺点,在不同的浏览器和how this behaves in event handlers的各种方式。

让你自己熟悉DOM interface也是很有帮助的。