[英]Javascript error when calling javascript library function
I have been developing a javascript library called TechX. 我一直在开发一个名为TechX的JavaScript库。 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();')
." 当我加载页面时,没有错误,但是当我单击按钮时,出现一个错误,指出“
'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. 在我看来,问题在于
tex("#test")
返回text.init
对象,但是.dit()
是tex
上的方法,而不是tex.init
上的方法,因此没有要执行的方法.dit()
。
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. 因此
.dit()
方法将基于您实际创建的对象的类型。
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: 或者,如果您打算使其像jQuery一样工作,则必须迭代所有包含的对象,如下所示:
dit : function(){
for (var i = 0; i < this.length; i++) {
this[i].innerHTML = 'Hi?!?!?!';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.