我一直在开发一个名为 TechX 的 JavaScript 库。这是代码:
(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;
})();
在我的体内,我有这个脚本来测试它:
<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>
当我加载页面时没有错误,但是当我单击按钮时,我收到一条错误,提示“'undefined' 不是一个函数(评估 'tex('#test').dit( );')
."
有谁知道我的代码做错了什么?我该如何修复该错误?非常感谢!
最佳答案
在我看来,问题在于 tex("#test")
返回一个 text.init
对象,但是 .dit()
是 tex
上的方法,而不是 tex.init
上的方法,因此没有方法 .dit()
可以执行。
也许您想更改此设置:
tex.prototype = {...}
对此:
tex.init.prototype = {...}
因此 .dit()
方法将采用您实际创建的对象的类型。
另外,我认为:
dit : function(){
this.innerHTML = 'Hi?!?!?!';
}
需要是这样的:
dit : function(){
this[0].innerHTML = 'Hi?!?!?!';
}
或者,如果您想让它像 jQuery 一样工作,您必须像这样迭代所有包含的对象:
dit : function(){
for (var i = 0; i < this.length; i++) {
this[i].innerHTML = 'Hi?!?!?!';
}
}
关于调用 javascript 库函数时出现 Javascript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19352018/