You would want a prototype. But the Object/Element prototypes aren't supported in all browsers. That's why jQuery creates its own object 'class' for all selectors and makes click() among other things a prototype of that 'class'. Remember, $('#someid') is not the same as document.getElementByID('someid').
Anyways, in at least some browsers you can do like:
Code:
Object.prototype.click = function(func) {
this.onclick = function() {
if(typeof func === "function") {
func();
}
}
};
I'm not sure if that would work exactly. If not, it's closer. Probably more like:
Code:
Object.prototype.click = function(func) {
if(typeof func === "function") {
this.onclick = func;
}
};
And as I say, not supported in all browsers.
However, the String prototype is supported in all browsers, so one could do this (tested and works):
Code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
(function(){
String.prototype.click = function(func){
var el = document.getElementById(this);
if(el){addEvent(el, 'click', func);}
};
var addEvent = (function(){return window.addEventListener? function(el, ev, f){
el.addEventListener(ev, f, false);
}:window.attachEvent? function(el, ev, f){
el.attachEvent('on' + ev, function(){var e = event; f.apply(el, [e]);});
}:function(){return;};
})();
})();
</script>
</head>
<body>
<a href="#" id="test">Test</a>
<script type="text/javascript">
('test').click(function(e){
alert("I'm " + this.innerHTML + ', You Clicked Me!');
e.preventDefault && e.preventDefault();
e.returnValue = false;
});
</script>
</body>
</html>
Bookmarks