Reputation: 9087
How do I execute a JS object's function property from an HTML link? I have the following 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");
};
Here is the HTML:
<script type="text/javascript">
var test = new Tester("test");
test.show();
</script>
When I click on the link that gets rendered, it cannot identify the test()
function. How would I get it so when a user clicks on the link, the test()
function is executed?
Upvotes: 1
Views: 278
Reputation: 817208
The proper way would be to create a DOM element and attach the event handler with 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);
};
Since the event handler forms a closure, it has access to the variables defined in the outer function (Tester.prototype.show
). Note that inside the event handler, this
does not refer to your instance, but to the element the handler is bound to (in this case a
). MDN has a good description of this
.
quirksmode.org has some great articles about event handling, the various ways you can bind event handlers, their advantages and disadvantages, differences in browsers and how this
behaves in event handlers.
It's also certainly helpful to make yourself familiar with the DOM interface.
Upvotes: 4