用于事件处理的 JavaScript 库出现奇怪的 'undefined' 错误

标签 javascript event-handling dom-events

我一直致力于开发一个用于事件处理的 JavaScript 库。以下是该库的一些代码:

01| (function(){
02|     var int,
03|         Jist = function(s){
04|             return new Jist.fn.init(s);
05|         };
06|     Jist.fn = Jist.prototype ={
07|         init : function(s){
08|             if(!s){
09|                 return this;
10|             }
11|             else{
12|                 this.length = 1;
13|                 if (typeof s === "object"){
14|                     this[0] = s;
15|                 }
16|                 else if(typeof s === "string"){
17|                     var obj;
18|                     obj = document.querySelectorAll(s);
19|                     this[0] = obj;
20|                     this.elem = this[0];
21|                 }
22|                 return this;
23|             }
24|         },
25|     };
26|     Jist.fx ={
27|         event : function(event,callback,state){
28|             var dummy = (state) ? false : state; 
29|             for(var i=0; i<this.elem.length; i++) {
30|                 this.elem[i].addEventListener(event,callback,dummy);
31|             }
32|             return this;
33|             },
34|     }
35|     Jist.fn.init.prototype = Jist.fn;
36|     Jist.fn.init.prototype = {
37|         print : function(txt){
38|             for(var i=0; i<this.elem.length; i++) {
39|                 this.elem[i].innerHTML = txt;
40|             }
41|             return this;
42|         },
43|         click : function(callback){
44|             Jist.fx.event("click",callback);
45|             return this;
46|         },
47|     };
48|     window.Jist = window._ = Jist;
49| })();

一切似乎都很好......

然后在我的网页上,这是我必须测试的内容:

01| <div id="enter">Begin!</div>
02| <script>
03|    _("#enter").click(function(){
04|       _("#enter").print("It worked!");
05|    })
06| </script>

这里看起来也不错。

看起来这应该可行,但我收到一个错误,内容如下:

'undefined' is not an object (evaluating this.elem.length)[line 29 in the library]

有谁知道如何修复这个错误?

非常感谢您的帮助。

最佳答案

您是否尝试过打印“this”的值?您确定在正确的范围内执行吗?

关于用于事件处理的 JavaScript 库出现奇怪的 'undefined' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19827711/

相关文章:

javascript - 在 React 中渲染组件 onClick

javascript - 使用 Javascript 添加两个数字时犯了什么错误

javascript - jQuery 1.10.2 选择器在 IE 中损坏了吗?

javascript - 使用 CasperJs 加载页面本身的同时加载页面的 Javascript

javascript - React 组件 - Plotly 图表创建器

c# - 需要解释使用 lambda 作为事件处理程序

JavaScript - 识别属性是否已定义并设置为 'undefined' 或未定义

C# - 为什么使用 EventHandler<T> 会出现错误?

c# - 检查事件处理程序是否存在

javascript - 汉字和 onkeypress 事件