从HTML调用JavaScript函数

时间:2012-05-20 00:26:56

标签: javascript

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

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()功能?

1 个答案:

答案 0 :(得分: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

也很有帮助