I have been developing a javascript library called TechX. Here is the code:
(function(){
function tex(s){
return new tex.init(s);
};
//declare the init selector function
tex.init = function(s){
if(!s){
return this;
}
else{
this.length = 1;
if (typeof s === "object"){
this[0] = s;
}
else if(typeof s === "string"){
var obj;
obj = document.querySelector(s);
this[0] = obj;
}
return this;
}
}
tex.prototype = {
dit : function(){
this.innerHTML = 'Hi?!?!?!';
}
};
window.tex = tex;
})();
In my body I have this script to test it out:
<input type="button" id="inpt" value="click"></input>
<div id="test"></div>
<script>
var inn = document.getElementById("inpt");
inn.onclick = function(){
tex('#test').dit();
};
</script>
When I load the page there are no errors, but when I click the button I get an error that says, " 'undefined' is not a function (evaluating 'tex('#test').dit();')
."
Does anyone know what I have done wrong in my code? How can I fix the error? Thank you so much!
It looks to me like the issue is that tex("#test")
returns a text.init
object, but .dit()
is a method on tex
, not on tex.init
so there's no method .dit()
to execute.
Perhaps you want to change this:
tex.prototype = {...}
to this:
tex.init.prototype = {...}
so the .dit()
method will be on the type of object you're actually creating.
Also, I think this:
dit : function(){
this.innerHTML = 'Hi?!?!?!';
}
needs to be this:
dit : function(){
this[0].innerHTML = 'Hi?!?!?!';
}
or, if you intend for it to work like jQuery, you'd have to iterate over all the contained objects like this:
dit : function(){
for (var i = 0; i < this.length; i++) {
this[i].innerHTML = 'Hi?!?!?!';
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.