html - Javascript add onclick unsuccessful -
my script :
function $(attr){ if(attr.charat(0) == "#"){ return document.getelementbyid(attr.substr(1)); }else{ if(attr.charat(0) == "."){ return document.getelementsbyclassname(attr.substr(1)); }else{ return document.getelementsbytagname(attr); } } } object.prototype.onclick = function(script){ this.onclick = script; } $("#hi").onclick(function(){alert("hi");});
in html it's label id hi
.
when click button, nothing happened. should do?
extending object
bad practice, wouldn't recommend it. in modern browsers want easy, can use queryselectorall, , add events addeventlistener:
// iife (immediately invoked function expression) var $ = (function() { // constructor function $(selector) { // queryselectorall returns pseudo-array this.el = toarray(document.queryselectorall(selector)); } // elements array or element index $.prototype.get = function(i) { return == null ? this.el : this.el[i]; }; // public method add event $.prototype.on = function(event, f) { this.el.foreach(function(el) { el.addeventlistener(event, f); }); // chain return this; }; // shortcut click event $.prototype.click = function(f) { return this.on('click', f); }; // coverts pseudo-arrays real arrays function toarray(x) { return array.prototype.slice.call(x); } // wrapper create instances // without using "new" keyword return function(x) { return new $(x); } }()); $('#hi').click(function(){alert('hi')});
Comments
Post a Comment